3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This class generates form components for processing a Contribution.
21 class CRM_Contribute_Form_Contribution_Main
extends CRM_Contribute_Form_ContributionBase
{
24 * Define default MembershipType Id.
27 public $_defaultMemTypeId;
29 public $_paymentProcessors;
31 public $_membershipTypeValues;
33 public $_useForMember;
36 * Array of payment related fields to potentially display on this form (generally credit card or debit card fields). This is rendered via billingBlock.tpl
39 public $_paymentFields = [];
41 protected $_paymentProcessorID;
45 * Set variables up before form is built.
47 public function preProcess() {
50 $this->_paymentProcessors
= $this->get('paymentProcessors');
51 $this->preProcessPaymentOptions();
53 $this->assignFormVariablesByContributionID();
55 // Make the contributionPageID available to the template
56 $this->assign('contributionPageID', $this->_id
);
57 $this->assign('ccid', $this->_ccid
);
58 $this->assign('isShare', CRM_Utils_Array
::value('is_share', $this->_values
));
59 $this->assign('isConfirmEnabled', CRM_Utils_Array
::value('is_confirm_enabled', $this->_values
));
61 // Required for currency formatting in the JS layer
62 // this is a temporary fix intended to resolve a regression quickly
63 // And assigning moneyFormat for js layer formatting
64 // will only work until that is done.
65 // https://github.com/civicrm/civicrm-core/pull/19151
66 $this->assign('moneyFormat', CRM_Utils_Money
::format(1234.56));
68 $this->assign('reset', CRM_Utils_Request
::retrieve('reset', 'Boolean'));
69 $this->assign('mainDisplay', CRM_Utils_Request
::retrieve('_qf_Main_display', 'Boolean',
70 CRM_Core_DAO
::$_nullObject));
72 if (!empty($this->_pcpInfo
['id']) && !empty($this->_pcpInfo
['intro_text'])) {
73 $this->assign('intro_text', $this->_pcpInfo
['intro_text']);
75 elseif (!empty($this->_values
['intro_text'])) {
76 $this->assign('intro_text', $this->_values
['intro_text']);
79 $qParams = "reset=1&id={$this->_id}";
80 if ($pcpId = CRM_Utils_Array
::value('pcp_id', $this->_pcpInfo
)) {
81 $qParams .= "&pcpId={$pcpId}";
83 $this->assign('qParams', $qParams);
85 if (!empty($this->_values
['footer_text'])) {
86 $this->assign('footer_text', $this->_values
['footer_text']);
91 * Set the default values.
93 public function setDefaultValues() {
94 // check if the user is registered and we have a contact ID
95 $contactID = $this->getContactID();
97 if (!empty($contactID)) {
99 $removeCustomFieldTypes = ['Contribution', 'Membership'];
100 $contribFields = CRM_Contribute_BAO_Contribution
::getContributionFields();
102 // remove component related fields
103 foreach ($this->_fields
as $name => $fieldInfo) {
104 //don't set custom data Used for Contribution (CRM-1344)
105 if (substr($name, 0, 7) == 'custom_') {
106 $id = substr($name, 7);
107 if (!CRM_Core_BAO_CustomGroup
::checkCustomField($id, $removeCustomFieldTypes)) {
110 // ignore component fields
112 elseif (array_key_exists($name, $contribFields) ||
(substr($name, 0, 11) == 'membership_') ||
(substr($name, 0, 13) == 'contribution_')) {
115 $fields[$name] = $fieldInfo;
118 if (!empty($fields)) {
119 CRM_Core_BAO_UFGroup
::setProfileDefaults($contactID, $fields, $this->_defaults
);
122 $billingDefaults = $this->getProfileDefaults('Billing', $contactID);
123 $this->_defaults
= array_merge($this->_defaults
, $billingDefaults);
125 if (!empty($this->_ccid
) && !empty($this->_pendingAmount
)) {
126 $this->_defaults
['total_amount'] = CRM_Utils_Money
::format($this->_pendingAmount
, NULL, '%a');
130 * hack to simplify credit card entry for testing
132 * $this->_defaults['credit_card_type'] = 'Visa';
133 * $this->_defaults['amount'] = 168;
134 * $this->_defaults['credit_card_number'] = '4111111111111111';
135 * $this->_defaults['cvv2'] = '000';
136 * $this->_defaults['credit_card_exp_date'] = array('Y' => date('Y')+1, 'M' => '05');
137 * // hack to simplify direct debit entry for testing
138 * $this->_defaults['account_holder'] = 'Max Müller';
139 * $this->_defaults['bank_account_number'] = '12345678';
140 * $this->_defaults['bank_identification_number'] = '12030000';
141 * $this->_defaults['bank_name'] = 'Bankname';
144 //build set default for pledge overdue payment.
145 if (!empty($this->_values
['pledge_id'])) {
146 //used to record completed pledge payment ids used later for honor default
147 $completedContributionIds = [];
148 $pledgePayments = CRM_Pledge_BAO_PledgePayment
::getPledgePayments($this->_values
['pledge_id']);
152 foreach ($pledgePayments as $payId => $value) {
153 if ($value['status'] == 'Overdue') {
154 $this->_defaults
['pledge_amount'][$payId] = 1;
155 $paymentAmount +
= $value['scheduled_amount'];
157 elseif (!$duePayment && $value['status'] == 'Pending') {
158 $this->_defaults
['pledge_amount'][$payId] = 1;
159 $paymentAmount +
= $value['scheduled_amount'];
162 elseif ($value['status'] == 'Completed' && $value['contribution_id']) {
163 $completedContributionIds[] = $value['contribution_id'];
166 $this->_defaults
['price_' . $this->_priceSetId
] = $paymentAmount;
168 if (count($completedContributionIds)) {
170 foreach ($completedContributionIds as $id) {
171 $softCredit = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($id);
173 if (isset($softCredit['soft_credit'])) {
174 $this->_defaults
['soft_credit_type_id'] = $softCredit['soft_credit'][1]['soft_credit_type'];
176 //since honoree profile fieldname of fields are prefixed with 'honor'
177 //we need to reformat the fieldname to append prefix during setting default values
178 CRM_Core_BAO_UFGroup
::setProfileDefaults(
179 $softCredit['soft_credit'][1]['contact_id'],
180 CRM_Core_BAO_UFGroup
::getFields($this->_honoreeProfileId
),
183 foreach ($defaults as $fieldName => $value) {
184 $this->_defaults
['honor[' . $fieldName . ']'] = $value;
189 elseif (!empty($this->_values
['pledge_block_id'])) {
190 //set default to one time contribution.
191 $this->_defaults
['is_pledge'] = 0;
194 // to process Custom data that are appended to URL
195 $getDefaults = CRM_Core_BAO_CustomGroup
::extractGetParams($this, "'Contact', 'Individual', 'Contribution'");
196 $this->_defaults
= array_merge($this->_defaults
, $getDefaults);
198 $config = CRM_Core_Config
::singleton();
199 // set default country from config if no country set
200 if (empty($this->_defaults
["billing_country_id-{$this->_bltID}"])) {
201 $this->_defaults
["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
204 // set default state/province from config if no state/province set
205 if (empty($this->_defaults
["billing_state_province_id-{$this->_bltID}"])) {
206 $this->_defaults
["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
209 $entityId = $memtypeID = NULL;
210 if ($this->_priceSetId
) {
211 if (($this->_useForMember
&& !empty($this->_currentMemberships
)) ||
$this->_defaultMemTypeId
) {
212 $selectedCurrentMemTypes = [];
213 foreach ($this->_priceSet
['fields'] as $key => $val) {
214 foreach ($val['options'] as $keys => $values) {
215 $opMemTypeId = $values['membership_type_id'] ??
NULL;
216 $priceFieldName = 'price_' . $values['price_field_id'];
217 $priceFieldValue = CRM_Price_BAO_PriceSet
::getPriceFieldValueFromURL($this, $priceFieldName);
218 if (!empty($priceFieldValue)) {
219 CRM_Price_BAO_PriceSet
::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $this->_defaults
);
220 // break here to prevent overwriting of default due to 'is_default'
221 // option configuration or setting of current membership or
222 // membership for related organization.
223 // The value sent via URL get's higher priority.
226 elseif ($opMemTypeId &&
227 in_array($opMemTypeId, $this->_currentMemberships
) &&
228 !in_array($opMemTypeId, $selectedCurrentMemTypes)
230 CRM_Price_BAO_PriceSet
::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $this->_defaults
);
231 $memtypeID = $selectedCurrentMemTypes[] = $values['membership_type_id'];
233 elseif (!empty($values['is_default']) && !$opMemTypeId && (!isset($this->_defaults
[$priceFieldName]) ||
234 ($val['html_type'] == 'CheckBox' && !isset($this->_defaults
[$priceFieldName][$keys])))) {
235 CRM_Price_BAO_PriceSet
::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $this->_defaults
);
236 $memtypeID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $this->_defaults
[$priceFieldName], 'membership_type_id');
240 $entityId = CRM_Utils_Array
::value('id', CRM_Member_BAO_Membership
::getContactMembership($contactID, $memtypeID, NULL));
243 CRM_Price_BAO_PriceSet
::setDefaultPriceSet($this, $this->_defaults
);
247 //set custom field defaults set by admin if value is not set
248 if (!empty($this->_fields
)) {
249 //load default campaign from page.
250 if (array_key_exists('contribution_campaign_id', $this->_fields
)) {
251 $this->_defaults
['contribution_campaign_id'] = $this->_values
['campaign_id'] ??
NULL;
254 //set custom field defaults
255 foreach ($this->_fields
as $name => $field) {
256 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
257 if (!isset($this->_defaults
[$name])) {
258 CRM_Core_BAO_CustomField
::setProfileDefaults($customFieldID, $name, $this->_defaults
,
259 $entityId, CRM_Profile_Form
::MODE_REGISTER
266 if (!empty($this->_paymentProcessors
)) {
267 foreach ($this->_paymentProcessors
as $pid => $value) {
268 if (!empty($value['is_default'])) {
269 $this->_defaults
['payment_processor_id'] = $pid;
274 return $this->_defaults
;
278 * Build the form object.
280 public function buildQuickForm() {
281 // build profiles first so that we can determine address fields etc
282 // and then show copy address checkbox
283 if (empty($this->_ccid
)) {
284 $this->buildCustom($this->_values
['custom_pre_id'], 'customPre');
285 $this->buildCustom($this->_values
['custom_post_id'], 'customPost');
287 // CRM-18399: used by template to pass pre profile id as a url arg
288 $this->assign('custom_pre_id', $this->_values
['custom_pre_id']);
290 $this->buildComponentForm($this->_id
, $this);
293 if (count($this->_paymentProcessors
) >= 1 && !$this->get_template_vars("isCaptcha") && $this->hasToAddForcefully()) {
294 if (!$this->_userID
) {
295 $this->enableCaptchaOnForm();
298 $this->displayCaptchaWarning();
302 // Build payment processor form
303 CRM_Core_Payment_ProcessorForm
::buildQuickForm($this);
305 $config = CRM_Core_Config
::singleton();
307 $contactID = $this->getContactID();
309 $this->assign('contact_id', $contactID);
310 $this->assign('display_name', CRM_Contact_BAO_Contact
::displayName($contactID));
313 $this->applyFilter('__ALL__', 'trim');
314 if (empty($this->_ccid
)) {
315 if ($this->_emailExists
== FALSE) {
316 $this->add('text', "email-{$this->_bltID}",
318 ['size' => 30, 'maxlength' => 60, 'class' => 'email'],
321 $this->assign('showMainEmail', TRUE);
322 $this->addRule("email-{$this->_bltID}", ts('Email is not valid.'), 'email');
326 $this->addElement('hidden', "email-{$this->_bltID}", 1);
327 $this->add('text', 'total_amount', ts('Total Amount'), ['readonly' => TRUE], FALSE);
329 $pps = $this->getProcessors();
330 $this->addPaymentProcessorFieldsToForm();
331 if (!empty($pps) && count($pps) === 1) {
332 $ppKeys = array_keys($pps);
333 $currentPP = array_pop($ppKeys);
334 if ($currentPP === 0) {
335 $this->assign('is_pay_later', $this->_values
['is_pay_later']);
336 $this->assign('pay_later_text', $this->getPayLaterLabel());
340 if ($contactID === 0) {
341 $this->addCidZeroOptions();
344 //build pledge block.
345 $this->_useForMember
= 0;
346 //don't build membership block when pledge_id is passed
347 if (empty($this->_values
['pledge_id']) && empty($this->_ccid
)) {
348 $this->_separateMembershipPayment
= FALSE;
349 if (in_array('CiviMember', $config->enableComponents
)) {
351 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
355 if ($this->_priceSetId
&&
356 (CRM_Core_Component
::getComponentID('CiviMember') == CRM_Utils_Array
::value('extends', $this->_priceSet
))
358 $this->_useForMember
= 1;
359 $this->set('useForMember', $this->_useForMember
);
362 $this->_separateMembershipPayment
= $this->buildMembershipBlock(
363 $this->_membershipContactID
,
368 $this->set('separateMembershipPayment', $this->_separateMembershipPayment
);
370 $this->assign('useForMember', $this->_useForMember
);
371 // If we configured price set for contribution page
372 // we are not allow membership signup as well as any
373 // other contribution amount field, CRM-5095
374 if (isset($this->_priceSetId
) && $this->_priceSetId
) {
375 $this->add('hidden', 'priceSetId', $this->_priceSetId
);
376 // build price set form.
377 $this->set('priceSetId', $this->_priceSetId
);
378 if (empty($this->_ccid
)) {
379 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
381 if ($this->_values
['is_monetary'] &&
382 $this->_values
['is_recur'] && empty($this->_values
['pledge_id'])
384 self
::buildRecur($this);
388 if ($this->_priceSetId
&& empty($this->_ccid
)) {
389 $is_quick_config = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config');
390 if ($is_quick_config) {
391 $this->_useForMember
= 0;
392 $this->set('useForMember', $this->_useForMember
);
396 //we allow premium for pledge during pledge creation only.
397 if (empty($this->_values
['pledge_id']) && empty($this->_ccid
)) {
398 CRM_Contribute_BAO_Premium
::buildPremiumBlock($this, $this->_id
, TRUE);
401 //don't build pledge block when mid is passed
402 if (!$this->_mid
&& empty($this->_ccid
)) {
403 $config = CRM_Core_Config
::singleton();
404 if (in_array('CiviPledge', $config->enableComponents
) && !empty($this->_values
['pledge_block_id'])) {
405 CRM_Pledge_BAO_PledgeBlock
::buildPledgeBlock($this);
409 //to create an cms user
410 if (!$this->_contactID
&& empty($this->_ccid
)) {
411 $createCMSUser = FALSE;
413 if ($this->_values
['custom_pre_id']) {
414 $profileID = $this->_values
['custom_pre_id'];
415 $createCMSUser = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_cms_user');
418 if (!$createCMSUser &&
419 $this->_values
['custom_post_id']
421 if (!is_array($this->_values
['custom_post_id'])) {
422 $profileIDs = [$this->_values
['custom_post_id']];
425 $profileIDs = $this->_values
['custom_post_id'];
427 foreach ($profileIDs as $pid) {
428 if (CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $pid, 'is_cms_user')) {
430 $createCMSUser = TRUE;
436 if ($createCMSUser) {
437 CRM_Core_BAO_CMSUser
::buildForm($this, $profileID, TRUE);
440 if ($this->_pcpId
&& empty($this->_ccid
)) {
441 if (CRM_PCP_BAO_PCP
::displayName($this->_pcpId
)) {
442 $pcp_supporter_text = CRM_PCP_BAO_PCP
::getPcpSupporterText($this->_pcpId
, $this->_id
, 'contribute');
443 $this->assign('pcpSupporterText', $pcp_supporter_text);
445 $prms = ['id' => $this->_pcpId
];
446 CRM_Core_DAO
::commonRetrieve('CRM_PCP_DAO_PCP', $prms, $pcpInfo);
447 if ($pcpInfo['is_honor_roll']) {
448 $this->assign('isHonor', TRUE);
449 $this->add('checkbox', 'pcp_display_in_roll', ts('Show my contribution in the public honor roll'), NULL, NULL,
450 ['onclick' => "showHideByValue('pcp_display_in_roll','','nameID|nickID|personalNoteID','block','radio',false); pcpAnonymous( );"]
452 $extraOption = ['onclick' => "return pcpAnonymous( );"];
453 $this->addRadio('pcp_is_anonymous', NULL, [ts('Include my name and message'), ts('List my contribution anonymously')], [], ' ', FALSE, [$extraOption, $extraOption]);
455 $this->add('text', 'pcp_roll_nickname', ts('Name'), ['maxlength' => 30]);
456 $this->addField('pcp_personal_note', ['entity' => 'ContributionSoft', 'context' => 'create', 'style' => 'height: 3em; width: 40em;']);
459 if (empty($this->_values
['fee']) && empty($this->_ccid
)) {
460 throw new CRM_Core_Exception(ts('This page does not have any price fields configured or you may not have permission for them. Please contact the site administrator for more details.'));
463 //we have to load confirm contribution button in template
464 //when multiple payment processor as the user
465 //can toggle with payment processor selection
466 $billingModePaymentProcessors = 0;
467 if (!empty($this->_paymentProcessors
)) {
468 foreach ($this->_paymentProcessors
as $key => $values) {
469 if ($values['billing_mode'] == CRM_Core_Payment
::BILLING_MODE_BUTTON
) {
470 $billingModePaymentProcessors++
;
475 if ($billingModePaymentProcessors && count($this->_paymentProcessors
) == $billingModePaymentProcessors) {
476 $allAreBillingModeProcessors = TRUE;
479 $allAreBillingModeProcessors = FALSE;
482 if (!($allAreBillingModeProcessors && !$this->_values
['is_pay_later'])) {
485 'name' => ts('Contribute'),
486 'spacing' => ' ',
489 if (!empty($this->_values
['is_confirm_enabled'])) {
490 $submitButton['name'] = ts('Review your contribution');
491 $submitButton['icon'] = 'fa-chevron-right';
493 // Add submit-once behavior when confirm page disabled
494 if (empty($this->_values
['is_confirm_enabled'])) {
495 $this->submitOnce
= TRUE;
497 //change button name for updating contribution
498 if (!empty($this->_ccid
)) {
499 $submitButton['name'] = ts('Confirm Payment');
501 $this->addButtons([$submitButton]);
504 $this->addFormRule(['CRM_Contribute_Form_Contribution_Main', 'formRule'], $this);
508 * Build Membership Block in Contribution Pages.
509 * @todo this was shared on CRM_Contribute_Form_ContributionBase but we are refactoring and simplifying for each
510 * step (main/confirm/thankyou)
513 * Contact checked for having a current membership for a particular membership.
514 * @param bool $isContributionMainPage
515 * Is this the main page? If so add form input fields.
516 * (or better yet don't have this functionality in a function shared with forms that don't share it).
517 * @param int|array $selectedMembershipTypeID
518 * Selected membership id.
519 * @param bool $thankPage
521 * @param null $isTest
524 * Is this a separate membership payment
526 * @throws \CiviCRM_API3_Exception
527 * @throws \CRM_Core_Exception
529 protected function buildMembershipBlock(
531 $isContributionMainPage = FALSE,
532 $selectedMembershipTypeID = NULL,
537 $separateMembershipPayment = FALSE;
538 if ($this->_membershipBlock
) {
539 $this->_currentMemberships
= [];
541 $membershipTypeIds = $membershipTypes = $radio = $radioOptAttrs = [];
542 $membershipPriceset = (!empty($this->_priceSetId
) && $this->_useForMember
);
544 $allowAutoRenewMembership = $autoRenewOption = FALSE;
545 $autoRenewMembershipTypeOptions = [];
547 $separateMembershipPayment = $this->_membershipBlock
['is_separate_payment'] ??
NULL;
549 if ($membershipPriceset) {
550 foreach ($this->_priceSet
['fields'] as $pField) {
551 if (empty($pField['options'])) {
554 foreach ($pField['options'] as $opId => $opValues) {
555 if (empty($opValues['membership_type_id'])) {
558 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
562 elseif (!empty($this->_membershipBlock
['membership_types'])) {
563 $membershipTypeIds = explode(',', $this->_membershipBlock
['membership_types']);
566 if (!empty($membershipTypeIds)) {
567 //set status message if wrong membershipType is included in membershipBlock
568 if (isset($this->_mid
) && !$membershipPriceset) {
569 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
573 if (!in_array($membershipTypeID, $membershipTypeIds)) {
574 CRM_Core_Session
::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Invalid Membership'), 'error');
578 $membershipTypeValues = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIds);
579 $this->_membershipTypeValues
= $membershipTypeValues;
582 // Check if we support auto-renew on this contribution page
583 // FIXME: If any of the payment processors do NOT support recurring you cannot setup an
584 // auto-renew payment even if that processor is not selected.
585 $allowAutoRenewOpt = TRUE;
586 if (is_array($this->_paymentProcessors
)) {
587 foreach ($this->_paymentProcessors
as $id => $val) {
588 if ($id && !$val['is_recur']) {
589 $allowAutoRenewOpt = FALSE;
593 foreach ($membershipTypeIds as $value) {
594 $memType = $membershipTypeValues[$value];
595 if ($selectedMembershipTypeID != NULL) {
596 if ($memType['id'] == $selectedMembershipTypeID) {
597 $this->assign('minimum_fee', $memType['minimum_fee'] ??
NULL);
598 $this->assign('membership_name', $memType['name']);
599 if (!$thankPage && $cid) {
600 $membership = new CRM_Member_DAO_Membership();
601 $membership->contact_id
= $cid;
602 $membership->membership_type_id
= $memType['id'];
603 if ($membership->find(TRUE)) {
604 $this->assign('renewal_mode', TRUE);
605 $memType['current_membership'] = $membership->end_date
;
606 $this->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
609 $membershipTypes[] = $memType;
612 elseif ($memType['is_active']) {
614 if ($allowAutoRenewOpt) {
615 $javascriptMethod = ['onclick' => "return showHideAutoRenew( this.value );"];
616 $isAvailableAutoRenew = $this->_membershipBlock
['auto_renew'][$value] ??
1;
617 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int) $memType['auto_renew'] * $isAvailableAutoRenew;
618 $allowAutoRenewMembership = TRUE;
621 $javascriptMethod = NULL;
622 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = 0;
625 //add membership type.
626 $radio[$memType['id']] = NULL;
627 $radioOptAttrs[$memType['id']] = $javascriptMethod;
629 $membership = new CRM_Member_DAO_Membership();
630 $membership->contact_id
= $cid;
631 $membership->membership_type_id
= $memType['id'];
633 //show current membership, skip pending and cancelled membership records,
634 //because we take first membership record id for renewal
635 $membership->whereAdd('status_id != 5 AND status_id !=6');
637 if (!is_null($isTest)) {
638 $membership->is_test
= $isTest;
642 $membership->orderBy('end_date DESC');
644 if ($membership->find(TRUE)) {
645 if (!$membership->end_date
) {
646 unset($radio[$memType['id']]);
647 unset($radioOptAttrs[$memType['id']]);
648 $this->assign('islifetime', TRUE);
651 $this->assign('renewal_mode', TRUE);
652 $this->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
653 $memType['current_membership'] = $membership->end_date
;
655 $endDate = $memType['current_membership'];
656 $this->_defaultMemTypeId
= $memType['id'];
658 if ($memType['current_membership'] < $endDate) {
659 $endDate = $memType['current_membership'];
660 $this->_defaultMemTypeId
= $memType['id'];
664 $membershipTypes[] = $memType;
669 $this->assign('membershipBlock', $this->_membershipBlock
);
670 $this->assign('showRadio', $isContributionMainPage);
671 $this->assign('membershipTypes', $membershipTypes);
672 $this->assign('allowAutoRenewMembership', $allowAutoRenewMembership);
673 $this->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
674 //give preference to user submitted auto_renew value.
675 $takeUserSubmittedAutoRenew = (!empty($_POST) ||
$this->isSubmitted());
676 $this->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
678 // Assign autorenew option (0:hide,1:optional,2:required) so we can use it in confirmation etc.
679 $autoRenewOption = CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($this->_priceSetId
);
680 //$selectedMembershipTypeID is retrieved as an array for membership priceset if multiple
681 //options for different organisation is selected on the contribution page.
682 if (is_numeric($selectedMembershipTypeID) && isset($membershipTypeValues[$selectedMembershipTypeID]['auto_renew'])) {
683 $this->assign('autoRenewOption', $membershipTypeValues[$selectedMembershipTypeID]['auto_renew']);
686 $this->assign('autoRenewOption', $autoRenewOption);
689 if ($isContributionMainPage) {
690 if (!$membershipPriceset) {
691 if (!$this->_membershipBlock
['is_required']) {
692 $this->assign('showRadioNoThanks', TRUE);
693 $radio['no_thanks'] = NULL;
694 $this->addRadio('selectMembership', NULL, $radio, [], NULL, FALSE, $radioOptAttrs);
696 elseif ($this->_membershipBlock
['is_required'] && count($radio) == 1) {
697 $temp = array_keys($radio);
698 $this->add('hidden', 'selectMembership', $temp[0], ['id' => 'selectMembership']);
699 $this->assign('singleMembership', TRUE);
700 $this->assign('showRadio', FALSE);
703 foreach ($radioOptAttrs as $opt => $attrs) {
704 $attrs['class'] = ' required';
706 $this->addRadio('selectMembership', NULL, $radio, [], NULL, FALSE, $radioOptAttrs);
709 $this->addRule('selectMembership', ts('Please select one of the memberships.'), 'required');
712 if ((!$this->_values
['is_pay_later'] ||
is_array($this->_paymentProcessors
)) && ($allowAutoRenewMembership ||
$autoRenewOption)) {
713 if ($autoRenewOption == 2) {
714 $this->addElement('hidden', 'auto_renew', ts('Please renew my membership automatically.'));
717 $this->addElement('checkbox', 'auto_renew', ts('Please renew my membership automatically.'));
724 return $separateMembershipPayment;
728 * Build elements to collect information for recurring contributions.
731 * @param CRM_Core_Form $form
733 public static function buildRecur(&$form) {
734 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_ContributionRecur');
735 $className = get_class($form);
737 $form->assign('is_recur_interval', CRM_Utils_Array
::value('is_recur_interval', $form->_values
));
738 $form->assign('is_recur_installments', CRM_Utils_Array
::value('is_recur_installments', $form->_values
));
739 $paymentObject = $form->getVar('_paymentObject');
740 if ($paymentObject) {
741 $form->assign('recurringHelpText', $paymentObject->getText('contributionPageRecurringHelp', [
742 'is_recur_installments' => !empty($form->_values
['is_recur_installments']),
743 'is_email_receipt' => !empty($form->_values
['is_email_receipt']),
747 $form->add('checkbox', 'is_recur', ts('I want to contribute this amount'), NULL);
749 if (!empty($form->_values
['is_recur_interval']) ||
$className == 'CRM_Contribute_Form_Contribution') {
750 $form->add('text', 'frequency_interval', ts('Every'), $attributes['frequency_interval'] +
['aria-label' => ts('Every')]);
751 $form->addRule('frequency_interval', ts('Frequency must be a whole number (EXAMPLE: Every 3 months).'), 'integer');
754 // make sure frequency_interval is submitted as 1 if given no choice to user.
755 $form->add('hidden', 'frequency_interval', 1);
758 $frUnits = $form->_values
['recur_frequency_unit'] ??
NULL;
759 if (empty($frUnits) &&
760 $className == 'CRM_Contribute_Form_Contribution'
762 $frUnits = implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
763 CRM_Core_OptionGroup
::values('recur_frequency_units')
767 $unitVals = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $frUnits);
769 // CRM 10860, display text instead of a dropdown if there's only 1 frequency unit
770 if (count($unitVals) == 1) {
771 $form->assign('one_frequency_unit', TRUE);
772 $unit = $unitVals[0];
773 $form->add('hidden', 'frequency_unit', $unit);
774 if (!empty($form->_values
['is_recur_interval']) ||
$className == 'CRM_Contribute_Form_Contribution') {
777 $form->assign('frequency_unit', $unit);
780 $form->assign('one_frequency_unit', FALSE);
782 $frequencyUnits = CRM_Core_OptionGroup
::values('recur_frequency_units', FALSE, FALSE, TRUE);
783 foreach ($unitVals as $key => $val) {
784 if (array_key_exists($val, $frequencyUnits)) {
785 $units[$val] = $frequencyUnits[$val];
786 if (!empty($form->_values
['is_recur_interval']) ||
$className == 'CRM_Contribute_Form_Contribution') {
787 $units[$val] = "{$frequencyUnits[$val]}(s)";
791 $frequencyUnit = &$form->addElement('select', 'frequency_unit', NULL, $units, ['aria-label' => ts('Frequency Unit')]);
794 // FIXME: Ideally we should freeze select box if there is only
795 // one option but looks there is some problem /w QF freeze.
796 //if ( count( $units ) == 1 ) {
797 //$frequencyUnit->freeze( );
800 $form->add('text', 'installments', ts('installments'),
801 $attributes['installments']
803 $form->addRule('installments', ts('Number of installments must be a whole number.'), 'integer');
809 * @param array $fields
810 * The input form values.
811 * @param array $files
812 * The uploaded files if any.
813 * @param \CRM_Contribute_Form_Contribution_Main $self
816 * true if no errors, else array of errors
818 public static function formRule($fields, $files, $self) {
820 $amount = self
::computeAmount($fields, $self->_values
);
821 if (!empty($fields['auto_renew']) && empty($fields['payment_processor_id'])) {
822 $errors['auto_renew'] = ts('You cannot have auto-renewal on if you are paying later.');
825 if ((!empty($fields['selectMembership']) &&
826 $fields['selectMembership'] != 'no_thanks'
828 (!empty($fields['priceSetId']) &&
832 $isTest = $self->_action
& CRM_Core_Action
::PREVIEW
;
833 $lifeMember = CRM_Member_BAO_Membership
::getAllContactMembership($self->_membershipContactID
, $isTest, TRUE);
835 $membershipOrgDetails = CRM_Member_BAO_MembershipType
::getAllMembershipTypes();
837 foreach (array_keys($lifeMember) as $memTypeId) {
838 $unallowedOrgs[] = $membershipOrgDetails[$memTypeId]['member_of_contact_id'];
842 //check for atleast one pricefields should be selected
843 if (!empty($fields['priceSetId']) && empty($self->_ccid
)) {
844 $priceField = new CRM_Price_DAO_PriceField();
845 $priceField->price_set_id
= $fields['priceSetId'];
846 $priceField->orderBy('weight');
850 $membershipIsActive = TRUE;
851 $previousId = $otherAmount = FALSE;
852 while ($priceField->fetch()) {
854 if ($self->isQuickConfig() && ($priceField->name
== 'contribution_amount' ||
$priceField->name
== 'membership_amount')) {
855 $previousId = $priceField->id
;
856 if ($priceField->name
== 'membership_amount' && !$priceField->is_active
) {
857 $membershipIsActive = FALSE;
860 if ($priceField->name
== 'other_amount') {
861 if ($self->_quickConfig
&& empty($fields["price_{$priceField->id}"]) &&
862 array_key_exists("price_{$previousId}", $fields) && isset($fields["price_{$previousId}"]) && $self->_values
['fee'][$previousId]['name'] == 'contribution_amount' && empty($fields["price_{$previousId}"])
864 $otherAmount = $priceField->id
;
866 elseif (!empty($fields["price_{$priceField->id}"])) {
867 $otherAmountVal = CRM_Utils_Rule
::cleanMoney($fields["price_{$priceField->id}"]);
868 $min = $self->_values
['min_amount'] ??
NULL;
869 $max = $self->_values
['max_amount'] ??
NULL;
870 if ($min && $otherAmountVal < $min) {
871 $errors["price_{$priceField->id}"] = ts('Contribution amount must be at least %1',
875 if ($max && $otherAmountVal > $max) {
876 $errors["price_{$priceField->id}"] = ts('Contribution amount cannot be more than %1.',
882 if (!empty($fields["price_{$priceField->id}"]) ||
($previousId == $priceField->id
&& isset($fields["price_{$previousId}"])
883 && empty($fields["price_{$previousId}"]))
885 $check[] = $priceField->id
;
889 $currentMemberships = NULL;
890 if ($membershipIsActive) {
891 $is_test = $self->_mode
!= 'live' ?
1 : 0;
892 $memContactID = $self->_membershipContactID
;
894 // For anonymous user check using dedupe rule
895 // if user has Cancelled Membership
896 if (!$memContactID) {
897 $memContactID = CRM_Contact_BAO_Contact
::getFirstDuplicateContact($fields, 'Individual', 'Unsupervised', [], FALSE);
899 $currentMemberships = CRM_Member_BAO_Membership
::getContactsCancelledMembership($memContactID,
903 foreach ($self->_values
['fee'] as $fieldKey => $fieldValue) {
904 if ($fieldValue['html_type'] != 'Text' && !empty($fields['price_' . $fieldKey])) {
905 if (!is_array($fields['price_' . $fieldKey]) && isset($fieldValue['options'][$fields['price_' . $fieldKey]])) {
906 if (array_key_exists('membership_type_id', $fieldValue['options'][$fields['price_' . $fieldKey]])
907 && in_array($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'], $currentMemberships)
909 $errors['price_' . $fieldKey] = ts('Your %1 membership was previously cancelled and can not be renewed online. Please contact the site administrator for assistance.', [1 => CRM_Member_PseudoConstant
::membershipType($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'])]);
913 if (is_array($fields['price_' . $fieldKey])) {
914 foreach (array_keys($fields['price_' . $fieldKey]) as $key) {
915 if (array_key_exists('membership_type_id', $fieldValue['options'][$key])
916 && in_array($fieldValue['options'][$key]['membership_type_id'], $currentMemberships)
918 $errors['price_' . $fieldKey] = ts('Your %1 membership was previously cancelled and can not be renewed online. Please contact the site administrator for assistance.', [1 => CRM_Member_PseudoConstant
::membershipType($fieldValue['options'][$key]['membership_type_id'])]);
928 if ($membershipIsActive && empty($self->_membershipBlock
['is_required'])
929 && $self->_values
['amount_block_is_active']
931 $membershipFieldId = $contributionFieldId = $errorKey = $otherFieldId = NULL;
932 foreach ($self->_values
['fee'] as $fieldKey => $fieldValue) {
933 // if 'No thank you' membership is selected then set $membershipFieldId
934 if ($fieldValue['name'] == 'membership_amount' && CRM_Utils_Array
::value('price_' . $fieldKey, $fields) == 0) {
935 $membershipFieldId = $fieldKey;
937 elseif ($membershipFieldId) {
938 if ($fieldValue['name'] == 'other_amount') {
939 $otherFieldId = $fieldKey;
941 elseif ($fieldValue['name'] == 'contribution_amount') {
942 $contributionFieldId = $fieldKey;
945 if (!$errorKey || CRM_Utils_Array
::value('price_' . $contributionFieldId, $fields) == '0') {
946 $errorKey = $fieldKey;
950 // $membershipFieldId is set and additional amount is 'No thank you' or NULL then throw error
951 if ($membershipFieldId && !(CRM_Utils_Array
::value('price_' . $contributionFieldId, $fields, -1) > 0) && empty($fields['price_' . $otherFieldId])) {
952 $errors["price_{$errorKey}"] = ts('Additional Contribution is required.');
955 if (empty($check) && empty($self->_ccid
)) {
956 if ($self->_useForMember
== 1 && $membershipIsActive) {
957 $errors['_qf_default'] = ts('Select at least one option from Membership Type(s).');
960 $errors['_qf_default'] = ts('Select at least one option from Contribution(s).');
963 if ($otherAmount && !empty($check)) {
964 $errors["price_{$otherAmount}"] = ts('Amount is required field.');
967 if ($self->_useForMember
== 1 && !empty($check) && $membershipIsActive) {
969 $priceFieldMemTypes = [];
971 foreach ($self->_priceSet
['fields'] as $priceId => $value) {
972 if (!empty($fields['price_' . $priceId]) ||
($self->_quickConfig
&& $value['name'] == 'membership_amount' && empty($self->_membershipBlock
['is_required']))) {
973 if (!empty($fields['price_' . $priceId]) && is_array($fields['price_' . $priceId])) {
974 foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) {
976 $priceFieldIDS[] = $priceFldVal;
980 elseif (!$value['is_enter_qty'] && !empty($fields['price_' . $priceId])) {
981 // The check for {!$value['is_enter_qty']} is done since, quantity fields allow entering
982 // quantity. And the quantity can't be conisdered as civicrm_price_field_value.id, CRM-9577
983 $priceFieldIDS[] = $fields['price_' . $priceId];
986 if (!empty($value['options'])) {
987 foreach ($value['options'] as $val) {
988 if (!empty($val['membership_type_id']) && (
989 ($fields['price_' . $priceId] == $val['id']) ||
990 (isset($fields['price_' . $priceId]) && !empty($fields['price_' . $priceId][$val['id']]))
993 $priceFieldMemTypes[] = $val['membership_type_id'];
1000 if (!empty($lifeMember)) {
1001 foreach ($priceFieldIDS as $priceFieldId) {
1002 if (($id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) &&
1003 in_array($membershipOrgDetails[$id]['member_of_contact_id'], $unallowedOrgs)
1005 $errors['_qf_default'] = ts('You already have a lifetime membership and cannot select a membership with a shorter term.');
1011 if (!empty($priceFieldIDS)) {
1012 $ids = implode(',', $priceFieldIDS);
1014 $priceFieldIDS['id'] = $fields['priceSetId'];
1015 $self->set('memberPriceFieldIDS', $priceFieldIDS);
1016 $count = CRM_Price_BAO_PriceSet
::getMembershipCount($ids);
1017 foreach ($count as $id => $occurrence) {
1018 if ($occurrence > 1) {
1019 $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.');
1025 if (empty($priceFieldMemTypes) && $self->_membershipBlock
['is_required'] == 1) {
1026 $errors['_qf_default'] = ts('Please select at least one membership option.');
1030 CRM_Price_BAO_PriceSet
::processAmount($self->_values
['fee'],
1034 $minAmt = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $fields['priceSetId'], 'min_amount');
1035 if ($fields['amount'] < 0) {
1036 $errors['_qf_default'] = ts('Contribution can not be less than zero. Please select the options accordingly');
1038 elseif (!empty($minAmt) && $fields['amount'] < $minAmt) {
1039 $errors['_qf_default'] = ts('A minimum amount of %1 should be selected from Contribution(s).', [
1040 1 => CRM_Utils_Money
::format($minAmt),
1044 $amount = $fields['amount'];
1047 if (isset($fields['selectProduct']) &&
1048 $fields['selectProduct'] != 'no_thanks'
1050 $productDAO = new CRM_Contribute_DAO_Product();
1051 $productDAO->id
= $fields['selectProduct'];
1052 $productDAO->find(TRUE);
1053 $min_amount = $productDAO->min_contribution
;
1055 if ($amount < $min_amount) {
1056 $errors['selectProduct'] = ts('The premium you have selected requires a minimum contribution of %1', [1 => CRM_Utils_Money
::format($min_amount)]);
1057 CRM_Core_Session
::setStatus($errors['selectProduct']);
1061 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
1062 CRM_Contribute_BAO_ContributionRecur
::validateRecurContribution($fields, $files, $self, $errors);
1064 if (!empty($fields['is_recur']) && empty($fields['payment_processor_id'])) {
1065 $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.');
1068 // validate PCP fields - if not anonymous, we need a nick name value
1069 if ($self->_pcpId
&& !empty($fields['pcp_display_in_roll']) &&
1070 empty($fields['pcp_is_anonymous']) &&
1071 CRM_Utils_Array
::value('pcp_roll_nickname', $fields) == ''
1073 $errors['pcp_roll_nickname'] = ts('Please enter a name to include in the Honor Roll, or select \'contribute anonymously\'.');
1076 // return if this is express mode
1077 $config = CRM_Core_Config
::singleton();
1078 if ($self->_paymentProcessor
&&
1079 (int) $self->_paymentProcessor
['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_BUTTON
1081 if (!empty($fields[$self->_expressButtonName
. '_x']) ||
!empty($fields[$self->_expressButtonName
. '_y']) ||
1082 !empty($fields[$self->_expressButtonName
])
1088 //validate the pledge fields.
1089 if (!empty($self->_values
['pledge_block_id'])) {
1090 //validation for pledge payment.
1091 if (!empty($self->_values
['pledge_id'])) {
1092 if (empty($fields['pledge_amount'])) {
1093 $errors['pledge_amount'] = ts('At least one payment option needs to be checked.');
1096 elseif (!empty($fields['is_pledge'])) {
1097 if (CRM_Utils_Rule
::positiveInteger(CRM_Utils_Array
::value('pledge_installments', $fields)) == FALSE) {
1098 $errors['pledge_installments'] = ts('Please enter a valid number of pledge installments.');
1101 if (!isset($fields['pledge_installments'])) {
1102 $errors['pledge_installments'] = ts('Pledge Installments is required field.');
1104 elseif (CRM_Utils_Array
::value('pledge_installments', $fields) == 1) {
1105 $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.');
1107 elseif (empty($fields['pledge_installments'])) {
1108 $errors['pledge_installments'] = ts('Pledge Installments field must be > 1.');
1112 //validation for Pledge Frequency Interval.
1113 if (CRM_Utils_Rule
::positiveInteger(CRM_Utils_Array
::value('pledge_frequency_interval', $fields)) == FALSE) {
1114 $errors['pledge_frequency_interval'] = ts('Please enter a valid Pledge Frequency Interval.');
1117 if (!isset($fields['pledge_frequency_interval'])) {
1118 $errors['pledge_frequency_interval'] = ts('Pledge Frequency Interval. is required field.');
1120 elseif (empty($fields['pledge_frequency_interval'])) {
1121 $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0');
1127 // if the user has chosen a free membership or the amount is less than zero
1128 // i.e. we don't need to validate payment related fields or profiles.
1129 if ((float) $amount <= 0.0) {
1133 if (!isset($fields['payment_processor_id'])) {
1134 $errors['payment_processor_id'] = ts('Payment Method is a required field.');
1137 CRM_Core_Payment_Form
::validatePaymentInstrument(
1138 $fields['payment_processor_id'],
1141 (!$self->_isBillingAddressRequiredForPayLater ?
NULL : 'billing')
1145 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1146 if ($greetingType = CRM_Utils_Array
::value($greeting, $fields)) {
1147 $customizedValue = CRM_Core_PseudoConstant
::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
1148 if ($customizedValue == $greetingType && empty($fielse[$greeting . '_custom'])) {
1149 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
1150 [1 => ucwords(str_replace('_', " ", $greeting))]
1156 return empty($errors) ?
TRUE : $errors;
1160 * Compute amount to be paid.
1162 * @param array $params
1163 * @param array $formValues
1165 * @return int|mixed|null|string
1167 public static function computeAmount($params, $formValues) {
1169 // First clean up the other amount field if present.
1170 if (isset($params['amount_other'])) {
1171 $params['amount_other'] = CRM_Utils_Rule
::cleanMoney($params['amount_other']);
1174 if (CRM_Utils_Array
::value('amount', $params) == 'amount_other_radio' ||
!empty($params['amount_other'])) {
1175 $amount = $params['amount_other'];
1177 elseif (!empty($params['pledge_amount'])) {
1178 foreach ($params['pledge_amount'] as $paymentId => $dontCare) {
1179 $amount +
= CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount');
1183 if (!empty($formValues['amount'])) {
1184 $amountID = $params['amount'] ??
NULL;
1187 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1188 // function to get correct amount level consistently. Remove setting of the amount level in
1189 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1190 // to cover all variants.
1191 $params['amount_level'] = $formValues[$amountID]['label'] ??
NULL;
1192 $amount = $formValues[$amountID]['value'] ??
NULL;
1200 * Process the form submission.
1202 public function postProcess() {
1203 // we first reset the confirm page so it accepts new values
1204 $this->controller
->resetPage('Confirm');
1206 // get the submitted form values.
1207 $params = $this->controller
->exportValues($this->_name
);
1208 $this->submit($params);
1210 if (empty($this->_values
['is_confirm_enabled'])) {
1211 $this->skipToThankYouPage();
1219 * This is the guts of the postProcess made also accessible to the test suite.
1221 * @param array $params
1224 * @throws \CiviCRM_API3_Exception
1226 public function submit($params) {
1227 //carry campaign from profile.
1228 if (array_key_exists('contribution_campaign_id', $params)) {
1229 $params['campaign_id'] = $params['contribution_campaign_id'];
1232 $params['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
1234 // @todo refactor this & leverage it from the unit tests.
1235 if (!empty($params['priceSetId'])) {
1236 $is_quick_config = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config');
1237 if ($is_quick_config) {
1238 $priceField = new CRM_Price_DAO_PriceField();
1239 $priceField->price_set_id
= $params['priceSetId'];
1240 $priceField->orderBy('weight');
1241 $priceField->find();
1244 while ($priceField->fetch()) {
1245 CRM_Price_BAO_PriceFieldValue
::getValues($priceField->id
, $priceOptions);
1246 if (($selectedPriceOptionID = CRM_Utils_Array
::value("price_{$priceField->id}", $params)) != FALSE && $selectedPriceOptionID > 0) {
1247 switch ($priceField->name
) {
1248 case 'membership_amount':
1249 $this->_params
['selectMembership'] = $params['selectMembership'] = $priceOptions[$selectedPriceOptionID]['membership_type_id'] ??
NULL;
1250 $this->set('selectMembership', $params['selectMembership']);
1252 case 'contribution_amount':
1253 $params['amount'] = $selectedPriceOptionID;
1254 if ($priceField->name
== 'contribution_amount' ||
1255 ($priceField->name
== 'membership_amount' &&
1256 CRM_Utils_Array
::value('is_separate_payment', $this->_membershipBlock
) == 0)
1258 $this->_values
['amount'] = $priceOptions[$selectedPriceOptionID]['amount'] ??
NULL;
1260 $this->_values
[$selectedPriceOptionID]['value'] = $priceOptions[$selectedPriceOptionID]['amount'] ??
NULL;
1261 $this->_values
[$selectedPriceOptionID]['label'] = $priceOptions[$selectedPriceOptionID]['label'] ??
NULL;
1262 $this->_values
[$selectedPriceOptionID]['amount_id'] = $priceOptions[$selectedPriceOptionID]['id'] ??
NULL;
1263 $this->_values
[$selectedPriceOptionID]['weight'] = $priceOptions[$selectedPriceOptionID]['weight'] ??
NULL;
1266 case 'other_amount':
1267 $params['amount_other'] = $selectedPriceOptionID;
1275 if (!empty($this->_ccid
) && !empty($this->_pendingAmount
)) {
1276 $params['amount'] = $this->_pendingAmount
;
1279 // from here on down, $params['amount'] holds a monetary value (or null) rather than an option ID
1280 $params['amount'] = self
::computeAmount($params, $this->_values
);
1283 $params['separate_amount'] = $params['amount'];
1284 // @todo - stepping through the code indicates that amount is always set before this point so it never matters.
1285 // Move more of the above into this function...
1286 $params['amount'] = $this->getMainContributionAmount($params);
1287 //If the membership & contribution is used in contribution page & not separate payment
1288 $memPresent = $membershipLabel = $fieldOption = $is_quick_config = NULL;
1289 $proceFieldAmount = 0;
1290 if (property_exists($this, '_separateMembershipPayment') && $this->_separateMembershipPayment
== 0) {
1291 $is_quick_config = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config');
1292 if ($is_quick_config) {
1293 foreach ($this->_priceSet
['fields'] as $fieldKey => $fieldVal) {
1294 if ($fieldVal['name'] == 'membership_amount' && !empty($params['price_' . $fieldKey])) {
1295 $fieldId = $fieldVal['id'];
1296 $fieldOption = $params['price_' . $fieldId];
1297 $proceFieldAmount +
= $fieldVal['options'][$this->_submitValues
['price_' . $fieldId]]['amount'];
1301 if (!empty($params['price_' . $fieldKey]) && $memPresent && ($fieldVal['name'] == 'other_amount' ||
$fieldVal['name'] == 'contribution_amount')) {
1302 $fieldId = $fieldVal['id'];
1303 if ($fieldVal['name'] == 'other_amount') {
1304 $proceFieldAmount +
= $this->_submitValues
['price_' . $fieldId];
1306 elseif ($fieldVal['name'] == 'contribution_amount' && $this->_submitValues
['price_' . $fieldId] > 0) {
1307 $proceFieldAmount +
= $fieldVal['options'][$this->_submitValues
['price_' . $fieldId]]['amount'];
1309 unset($params['price_' . $fieldId]);
1317 if (!isset($params['amount_other'])) {
1318 $this->set('amount_level', CRM_Utils_Array
::value('amount_level', $params));
1321 if (!empty($this->_ccid
)) {
1322 $this->set('lineItem', $this->_lineItem
);
1324 elseif ($priceSetId = CRM_Utils_Array
::value('priceSetId', $params)) {
1326 $is_quick_config = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1327 if ($is_quick_config) {
1328 foreach ($this->_values
['fee'] as $key => & $val) {
1329 if ($val['name'] == 'other_amount' && $val['html_type'] == 'Text' && !empty($params['price_' . $key])) {
1330 // Clean out any currency symbols.
1331 $params['price_' . $key] = CRM_Utils_Rule
::cleanMoney($params['price_' . $key]);
1332 if ($params['price_' . $key] != 0) {
1333 foreach ($val['options'] as $optionKey => & $options) {
1334 $options['amount'] = $params['price_' . $key] ??
NULL;
1338 $params['price_' . $key] = 1;
1344 if ($this->_membershipBlock
) {
1345 $this->processAmountAndGetAutoRenew($this->_values
['fee'], $params, $lineItem[$priceSetId], $priceSetId);
1348 CRM_Price_BAO_PriceSet
::processAmount($this->_values
['fee'], $params, $lineItem[$priceSetId], $priceSetId);
1351 if ($params['tax_amount']) {
1352 $this->set('tax_amount', $params['tax_amount']);
1355 if ($proceFieldAmount) {
1356 $lineItem[$params['priceSetId']][$fieldOption]['unit_price'] = $proceFieldAmount;
1357 $lineItem[$params['priceSetId']][$fieldOption]['line_total'] = $proceFieldAmount;
1358 if (isset($lineItem[$params['priceSetId']][$fieldOption]['tax_amount'])) {
1359 $proceFieldAmount +
= $lineItem[$params['priceSetId']][$fieldOption]['tax_amount'];
1361 if (!$this->_membershipBlock
['is_separate_payment']) {
1362 //require when separate membership not used
1363 $params['amount'] = $proceFieldAmount;
1366 $this->set('lineItem', $lineItem);
1369 if ($params['amount'] != 0 && (($this->_values
['is_pay_later'] &&
1370 empty($this->_paymentProcessor
) &&
1371 !array_key_exists('hidden_processor', $params)) ||
1372 empty($params['payment_processor_id']))
1374 $params['is_pay_later'] = 1;
1377 $params['is_pay_later'] = 0;
1380 // Would be nice to someday understand the point of this set.
1381 $this->set('is_pay_later', $params['is_pay_later']);
1382 // assign pay later stuff
1383 $this->_params
['is_pay_later'] = CRM_Utils_Array
::value('is_pay_later', $params, FALSE);
1384 $this->assign('is_pay_later', $params['is_pay_later']);
1385 if ($params['is_pay_later']) {
1386 $this->assign('pay_later_text', $this->_values
['pay_later_text']);
1387 $this->assign('pay_later_receipt', CRM_Utils_Array
::value('pay_later_receipt', $this->_values
));
1390 if ($this->_membershipBlock
&& $this->_membershipBlock
['is_separate_payment'] && !empty($params['separate_amount'])) {
1391 $this->set('amount', $params['separate_amount']);
1394 $this->set('amount', $params['amount']);
1397 // generate and set an invoiceID for this transaction
1398 $invoiceID = md5(uniqid(rand(), TRUE));
1399 $this->set('invoiceID', $invoiceID);
1400 $params['invoiceID'] = $invoiceID;
1401 $title = !empty($this->_values
['frontend_title']) ?
$this->_values
['frontend_title'] : $this->_values
['title'];
1402 $params['description'] = ts('Online Contribution') . ': ' . ((!empty($this->_pcpInfo
['title']) ?
$this->_pcpInfo
['title'] : $title));
1403 $params['button'] = $this->controller
->getButtonName();
1404 // required only if is_monetary and valid positive amount
1405 if ($this->_values
['is_monetary'] &&
1406 !empty($this->_paymentProcessor
) &&
1407 ((float) $params['amount'] > 0.0 ||
$this->hasSeparateMembershipPaymentAmount($params))
1409 // The concept of contributeMode is deprecated - as should be the 'is_monetary' setting.
1410 $this->setContributeMode();
1411 // Really this setting of $this->_params & params within it should be done earlier on in the function
1412 // probably the values determined here should be reused in confirm postProcess as there is no opportunity to alter anything
1413 // on the confirm page. However as we are dealing with a stable release we go as close to where it is used
1415 // In general the form has a lack of clarity of the logic of why things are set on the form in some cases &
1416 // the logic around when $this->_params is used compared to other params arrays.
1417 $this->_params
= array_merge($params, $this->_params
);
1418 $this->setRecurringMembershipParams();
1419 if ($this->_paymentProcessor
&&
1420 $this->_paymentProcessor
['object']->supports('preApproval')
1422 $this->handlePreApproval($this->_params
);
1428 * Assign the billing mode to the template.
1430 * This is required for legacy support for contributeMode in templates.
1432 * The goal is to remove this parameter & use more relevant parameters.
1434 protected function setContributeMode() {
1435 switch ($this->_paymentProcessor
['billing_mode']) {
1436 case CRM_Core_Payment
::BILLING_MODE_FORM
:
1437 $this->set('contributeMode', 'direct');
1440 case CRM_Core_Payment
::BILLING_MODE_BUTTON
:
1441 $this->set('contributeMode', 'express');
1444 case CRM_Core_Payment
::BILLING_MODE_NOTIFY
:
1445 $this->set('contributeMode', 'notify');
1452 * Process confirm function and pass browser to the thank you page.
1454 protected function skipToThankYouPage() {
1455 // call the post process hook for the main page before we switch to confirm
1456 $this->postProcessHook();
1458 // build the confirm page
1459 $confirmForm = &$this->controller
->_pages
['Confirm'];
1460 $confirmForm->preProcess();
1461 $confirmForm->buildQuickForm();
1463 // the confirmation page is valid
1464 $data = &$this->controller
->container();
1465 $data['valid']['Confirm'] = 1;
1467 // confirm the contribution
1468 // mainProcess calls the hook also
1469 $confirmForm->mainProcess();
1470 $qfKey = $this->controller
->_key
;
1472 // redirect to thank you page
1473 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_ThankYou_display=1&qfKey=$qfKey", TRUE, NULL, FALSE));
1477 * Set form variables if contribution ID is found
1479 public function assignFormVariablesByContributionID() {
1480 if (empty($this->_ccid
)) {
1483 if (!$this->getContactID()) {
1484 CRM_Core_Error
::statusBounce(ts("Returning since there is no contact attached to this contribution id."));
1487 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($this->_ccid
);
1488 //bounce if the contribution is not pending.
1489 if ((int) $paymentBalance <= 0) {
1490 CRM_Core_Error
::statusBounce(ts("Returning since contribution has already been handled."));
1492 if (!empty($paymentBalance)) {
1493 $this->_pendingAmount
= $paymentBalance;
1494 $this->assign('pendingAmount', $this->_pendingAmount
);
1497 if ($taxAmount = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_ccid
, 'tax_amount')) {
1498 $this->set('tax_amount', $taxAmount);
1499 $this->assign('taxAmount', $taxAmount);
1502 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->_ccid
);
1503 foreach (array_keys($lineItems) as $id) {
1504 $lineItems[$id]['id'] = $id;
1506 $itemId = key($lineItems);
1507 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1508 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1511 if (!empty($lineItems[$itemId]['price_field_id'])) {
1512 $this->_lineItem
[$this->_priceSetId
] = $lineItems;
1514 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config');
1515 $this->assign('lineItem', $this->_lineItem
);
1516 $this->assign('is_quick_config', $isQuickConfig);
1517 $this->assign('priceSetID', $this->_priceSetId
);
1521 * Function for unit tests on the postProcess function.
1523 * @param array $params
1525 * @throws \CiviCRM_API3_Exception
1527 public function testSubmit($params) {
1528 $_SERVER['REQUEST_METHOD'] = 'GET';
1529 $this->controller
= new CRM_Contribute_Controller_Contribution();
1530 $this->submit($params);
1534 * Has a separate membership payment amount been configured.
1536 * @param array $params
1539 * @throws \CiviCRM_API3_Exception
1541 protected function hasSeparateMembershipPaymentAmount($params) {
1542 return $this->_separateMembershipPayment
&& (int) CRM_Member_BAO_MembershipType
::getMembershipType($params['selectMembership'])['minimum_fee'];