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 processing a Contribution.
37 class CRM_Contribute_Form_Contribution_Main
extends CRM_Contribute_Form_ContributionBase
{
40 * Define default MembershipType Id.
43 public $_defaultMemTypeId;
45 public $_paymentProcessors;
47 public $_membershipTypeValues;
49 public $_useForMember;
52 * Array of payment related fields to potentially display on this form (generally credit card or debit card fields). This is rendered via billingBlock.tpl
55 public $_paymentFields = [];
57 protected $_paymentProcessorID;
61 * Set variables up before form is built.
63 public function preProcess() {
66 $this->_paymentProcessors
= $this->get('paymentProcessors');
67 $this->preProcessPaymentOptions();
69 $this->assignFormVariablesByContributionID();
71 // Make the contributionPageID available to the template
72 $this->assign('contributionPageID', $this->_id
);
73 $this->assign('ccid', $this->_ccid
);
74 $this->assign('isShare', CRM_Utils_Array
::value('is_share', $this->_values
));
75 $this->assign('isConfirmEnabled', CRM_Utils_Array
::value('is_confirm_enabled', $this->_values
));
77 $this->assign('reset', CRM_Utils_Request
::retrieve('reset', 'Boolean'));
78 $this->assign('mainDisplay', CRM_Utils_Request
::retrieve('_qf_Main_display', 'Boolean',
79 CRM_Core_DAO
::$_nullObject));
81 if (!empty($this->_pcpInfo
['id']) && !empty($this->_pcpInfo
['intro_text'])) {
82 $this->assign('intro_text', $this->_pcpInfo
['intro_text']);
84 elseif (!empty($this->_values
['intro_text'])) {
85 $this->assign('intro_text', $this->_values
['intro_text']);
88 $qParams = "reset=1&id={$this->_id}";
89 if ($pcpId = CRM_Utils_Array
::value('pcp_id', $this->_pcpInfo
)) {
90 $qParams .= "&pcpId={$pcpId}";
92 $this->assign('qParams', $qParams);
94 if (!empty($this->_values
['footer_text'])) {
95 $this->assign('footer_text', $this->_values
['footer_text']);
100 * Set the default values.
102 public function setDefaultValues() {
103 // check if the user is registered and we have a contact ID
104 $contactID = $this->getContactID();
106 if (!empty($contactID)) {
108 $removeCustomFieldTypes = ['Contribution', 'Membership'];
109 $contribFields = CRM_Contribute_BAO_Contribution
::getContributionFields();
111 // remove component related fields
112 foreach ($this->_fields
as $name => $dontCare) {
113 //don't set custom data Used for Contribution (CRM-1344)
114 if (substr($name, 0, 7) == 'custom_') {
115 $id = substr($name, 7);
116 if (!CRM_Core_BAO_CustomGroup
::checkCustomField($id, $removeCustomFieldTypes)) {
119 // ignore component fields
121 elseif (array_key_exists($name, $contribFields) ||
(substr($name, 0, 11) == 'membership_') ||
(substr($name, 0, 13) == 'contribution_')) {
127 if (!empty($fields)) {
128 CRM_Core_BAO_UFGroup
::setProfileDefaults($contactID, $fields, $this->_defaults
);
131 $billingDefaults = $this->getProfileDefaults('Billing', $contactID);
132 $this->_defaults
= array_merge($this->_defaults
, $billingDefaults);
134 if (!empty($this->_ccid
) && !empty($this->_pendingAmount
)) {
135 $this->_defaults
['total_amount'] = CRM_Utils_Money
::format($this->_pendingAmount
, NULL, '%a');
139 * hack to simplify credit card entry for testing
141 * $this->_defaults['credit_card_type'] = 'Visa';
142 * $this->_defaults['amount'] = 168;
143 * $this->_defaults['credit_card_number'] = '4111111111111111';
144 * $this->_defaults['cvv2'] = '000';
145 * $this->_defaults['credit_card_exp_date'] = array('Y' => date('Y')+1, 'M' => '05');
146 * // hack to simplify direct debit entry for testing
147 * $this->_defaults['account_holder'] = 'Max Müller';
148 * $this->_defaults['bank_account_number'] = '12345678';
149 * $this->_defaults['bank_identification_number'] = '12030000';
150 * $this->_defaults['bank_name'] = 'Bankname';
153 //build set default for pledge overdue payment.
154 if (!empty($this->_values
['pledge_id'])) {
155 //used to record completed pledge payment ids used later for honor default
156 $completedContributionIds = [];
157 $pledgePayments = CRM_Pledge_BAO_PledgePayment
::getPledgePayments($this->_values
['pledge_id']);
161 foreach ($pledgePayments as $payId => $value) {
162 if ($value['status'] == 'Overdue') {
163 $this->_defaults
['pledge_amount'][$payId] = 1;
164 $paymentAmount +
= $value['scheduled_amount'];
166 elseif (!$duePayment && $value['status'] == 'Pending') {
167 $this->_defaults
['pledge_amount'][$payId] = 1;
168 $paymentAmount +
= $value['scheduled_amount'];
171 elseif ($value['status'] == 'Completed' && $value['contribution_id']) {
172 $completedContributionIds[] = $value['contribution_id'];
175 $this->_defaults
['price_' . $this->_priceSetId
] = $paymentAmount;
177 if (count($completedContributionIds)) {
179 foreach ($completedContributionIds as $id) {
180 $softCredit = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($id);
182 if (isset($softCredit['soft_credit'])) {
183 $this->_defaults
['soft_credit_type_id'] = $softCredit['soft_credit'][1]['soft_credit_type'];
185 //since honoree profile fieldname of fields are prefixed with 'honor'
186 //we need to reformat the fieldname to append prefix during setting default values
187 CRM_Core_BAO_UFGroup
::setProfileDefaults(
188 $softCredit['soft_credit'][1]['contact_id'],
189 CRM_Core_BAO_UFGroup
::getFields($this->_honoreeProfileId
),
192 foreach ($defaults as $fieldName => $value) {
193 $this->_defaults
['honor[' . $fieldName . ']'] = $value;
198 elseif (!empty($this->_values
['pledge_block_id'])) {
199 //set default to one time contribution.
200 $this->_defaults
['is_pledge'] = 0;
203 // to process Custom data that are appended to URL
204 $getDefaults = CRM_Core_BAO_CustomGroup
::extractGetParams($this, "'Contact', 'Individual', 'Contribution'");
205 $this->_defaults
= array_merge($this->_defaults
, $getDefaults);
207 $config = CRM_Core_Config
::singleton();
208 // set default country from config if no country set
209 if (empty($this->_defaults
["billing_country_id-{$this->_bltID}"])) {
210 $this->_defaults
["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry
;
213 // set default state/province from config if no state/province set
214 if (empty($this->_defaults
["billing_state_province_id-{$this->_bltID}"])) {
215 $this->_defaults
["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince
;
218 $entityId = $memtypeID = NULL;
219 if ($this->_priceSetId
) {
220 if (($this->_useForMember
&& !empty($this->_currentMemberships
)) ||
$this->_defaultMemTypeId
) {
221 $selectedCurrentMemTypes = [];
222 foreach ($this->_priceSet
['fields'] as $key => $val) {
223 foreach ($val['options'] as $keys => $values) {
224 $opMemTypeId = CRM_Utils_Array
::value('membership_type_id', $values);
225 $priceFieldName = 'price_' . $values['price_field_id'];
226 $priceFieldValue = CRM_Price_BAO_PriceSet
::getPriceFieldValueFromURL($this, $priceFieldName);
227 if (!empty($priceFieldValue)) {
228 CRM_Price_BAO_PriceSet
::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $this->_defaults
);
229 // break here to prevent overwriting of default due to 'is_default'
230 // option configuration or setting of current membership or
231 // membership for related organization.
232 // The value sent via URL get's higher priority.
235 elseif ($opMemTypeId &&
236 in_array($opMemTypeId, $this->_currentMemberships
) &&
237 !in_array($opMemTypeId, $selectedCurrentMemTypes)
239 CRM_Price_BAO_PriceSet
::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $this->_defaults
);
240 $memtypeID = $selectedCurrentMemTypes[] = $values['membership_type_id'];
242 elseif (!empty($values['is_default']) && !$opMemTypeId && (!isset($this->_defaults
[$priceFieldName]) ||
243 ($val['html_type'] == 'CheckBox' && !isset($this->_defaults
[$priceFieldName][$keys])))) {
244 CRM_Price_BAO_PriceSet
::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $this->_defaults
);
245 $memtypeID = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $this->_defaults
[$priceFieldName], 'membership_type_id');
249 $entityId = CRM_Utils_Array
::value('id', CRM_Member_BAO_Membership
::getContactMembership($contactID, $memtypeID, NULL));
252 CRM_Price_BAO_PriceSet
::setDefaultPriceSet($this, $this->_defaults
);
256 //set custom field defaults set by admin if value is not set
257 if (!empty($this->_fields
)) {
258 //load default campaign from page.
259 if (array_key_exists('contribution_campaign_id', $this->_fields
)) {
260 $this->_defaults
['contribution_campaign_id'] = CRM_Utils_Array
::value('campaign_id', $this->_values
);
263 //set custom field defaults
264 foreach ($this->_fields
as $name => $field) {
265 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($name)) {
266 if (!isset($this->_defaults
[$name])) {
267 CRM_Core_BAO_CustomField
::setProfileDefaults($customFieldID, $name, $this->_defaults
,
268 $entityId, CRM_Profile_Form
::MODE_REGISTER
275 if (!empty($this->_paymentProcessors
)) {
276 foreach ($this->_paymentProcessors
as $pid => $value) {
277 if (!empty($value['is_default'])) {
278 $this->_defaults
['payment_processor_id'] = $pid;
283 return $this->_defaults
;
287 * Build the form object.
289 public function buildQuickForm() {
290 // build profiles first so that we can determine address fields etc
291 // and then show copy address checkbox
292 if (empty($this->_ccid
)) {
293 $this->buildCustom($this->_values
['custom_pre_id'], 'customPre');
294 $this->buildCustom($this->_values
['custom_post_id'], 'customPost');
296 // CRM-18399: used by template to pass pre profile id as a url arg
297 $this->assign('custom_pre_id', $this->_values
['custom_pre_id']);
299 $this->buildComponentForm($this->_id
, $this);
302 if (count($this->_paymentProcessors
) >= 1 && !isset($this->_paymentProcessors
[0]) && !$this->get_template_vars("isCaptcha") && $this->hasToAddForcefully()) {
303 if (!$this->_userID
) {
304 $this->enableCaptchaOnForm();
307 $this->displayCaptchaWarning();
311 // Build payment processor form
312 CRM_Core_Payment_ProcessorForm
::buildQuickForm($this);
314 $config = CRM_Core_Config
::singleton();
316 $contactID = $this->getContactID();
318 $this->assign('contact_id', $contactID);
319 $this->assign('display_name', CRM_Contact_BAO_Contact
::displayName($contactID));
322 $this->applyFilter('__ALL__', 'trim');
323 if (empty($this->_ccid
)) {
324 if ($this->_emailExists
== FALSE) {
325 $this->add('text', "email-{$this->_bltID}",
327 ['size' => 30, 'maxlength' => 60, 'class' => 'email'],
330 $this->assign('showMainEmail', TRUE);
331 $this->addRule("email-{$this->_bltID}", ts('Email is not valid.'), 'email');
335 $this->addElement('hidden', "email-{$this->_bltID}", 1);
336 $this->add('text', 'total_amount', ts('Total Amount'), ['readonly' => TRUE], FALSE);
339 //@todo - this should be replaced by a check as to whether billing fields are set
340 $onlinePaymentProcessorEnabled = FALSE;
341 if (!empty($this->_paymentProcessors
)) {
342 foreach ($this->_paymentProcessors
as $key => $name) {
343 if ($name['billing_mode'] == 1) {
344 $onlinePaymentProcessorEnabled = TRUE;
346 $pps[$key] = $name['name'];
349 if (!empty($this->_values
['is_pay_later'])) {
350 $pps[0] = $this->_values
['pay_later_text'];
353 if (count($pps) > 1) {
354 $this->addRadio('payment_processor_id', ts('Payment Method'), $pps,
358 elseif (!empty($pps)) {
359 $key = array_keys($pps);
360 $key = array_pop($key);
361 $this->addElement('hidden', 'payment_processor_id', $key);
363 $this->assign('is_pay_later', $this->_values
['is_pay_later']);
364 $this->assign('pay_later_text', $this->_values
['pay_later_text']);
368 $contactID = $this->getContactID();
369 if ($this->getContactID() === 0) {
370 $this->addCidZeroOptions($onlinePaymentProcessorEnabled);
373 //build pledge block.
374 $this->_useForMember
= 0;
375 //don't build membership block when pledge_id is passed
376 if (empty($this->_values
['pledge_id']) && empty($this->_ccid
)) {
377 $this->_separateMembershipPayment
= FALSE;
378 if (in_array('CiviMember', $config->enableComponents
)) {
380 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
384 if ($this->_priceSetId
&&
385 (CRM_Core_Component
::getComponentID('CiviMember') == CRM_Utils_Array
::value('extends', $this->_priceSet
))
387 $this->_useForMember
= 1;
388 $this->set('useForMember', $this->_useForMember
);
391 $this->_separateMembershipPayment
= $this->buildMembershipBlock(
392 $this->_membershipContactID
,
397 $this->set('separateMembershipPayment', $this->_separateMembershipPayment
);
399 $this->assign('useForMember', $this->_useForMember
);
400 // If we configured price set for contribution page
401 // we are not allow membership signup as well as any
402 // other contribution amount field, CRM-5095
403 if (isset($this->_priceSetId
) && $this->_priceSetId
) {
404 $this->add('hidden', 'priceSetId', $this->_priceSetId
);
405 // build price set form.
406 $this->set('priceSetId', $this->_priceSetId
);
407 if (empty($this->_ccid
)) {
408 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
410 if ($this->_values
['is_monetary'] &&
411 $this->_values
['is_recur'] && empty($this->_values
['pledge_id'])
413 self
::buildRecur($this);
417 if ($this->_priceSetId
&& empty($this->_ccid
)) {
418 $is_quick_config = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config');
419 if ($is_quick_config) {
420 $this->_useForMember
= 0;
421 $this->set('useForMember', $this->_useForMember
);
425 //we allow premium for pledge during pledge creation only.
426 if (empty($this->_values
['pledge_id']) && empty($this->_ccid
)) {
427 CRM_Contribute_BAO_Premium
::buildPremiumBlock($this, $this->_id
, TRUE);
430 //don't build pledge block when mid is passed
431 if (!$this->_mid
&& empty($this->_ccid
)) {
432 $config = CRM_Core_Config
::singleton();
433 if (in_array('CiviPledge', $config->enableComponents
) && !empty($this->_values
['pledge_block_id'])) {
434 CRM_Pledge_BAO_PledgeBlock
::buildPledgeBlock($this);
438 //to create an cms user
439 if (!$this->_contactID
&& empty($this->_ccid
)) {
440 $createCMSUser = FALSE;
442 if ($this->_values
['custom_pre_id']) {
443 $profileID = $this->_values
['custom_pre_id'];
444 $createCMSUser = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_cms_user');
447 if (!$createCMSUser &&
448 $this->_values
['custom_post_id']
450 if (!is_array($this->_values
['custom_post_id'])) {
451 $profileIDs = [$this->_values
['custom_post_id']];
454 $profileIDs = $this->_values
['custom_post_id'];
456 foreach ($profileIDs as $pid) {
457 if (CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFGroup', $pid, 'is_cms_user')) {
459 $createCMSUser = TRUE;
465 if ($createCMSUser) {
466 CRM_Core_BAO_CMSUser
::buildForm($this, $profileID, TRUE);
469 if ($this->_pcpId
&& empty($this->_ccid
)) {
470 if ($pcpSupporter = CRM_PCP_BAO_PCP
::displayName($this->_pcpId
)) {
471 $pcp_supporter_text = ts('This contribution is being made thanks to the effort of <strong>%1</strong>, who supports our campaign.', [1 => $pcpSupporter]);
472 // Only tell people that can also create a PCP if the contribution page has a non-empty value in the "Create Personal Campaign Page link" field.
473 $text = CRM_PCP_BAO_PCP
::getPcpBlockStatus($this->_id
, 'contribute');
475 $pcp_supporter_text .= ts("You can support it as well - once you complete the donation, you will be able to create your own Personal Campaign Page!");
477 $this->assign('pcpSupporterText', $pcp_supporter_text);
479 $prms = ['id' => $this->_pcpId
];
480 CRM_Core_DAO
::commonRetrieve('CRM_PCP_DAO_PCP', $prms, $pcpInfo);
481 if ($pcpInfo['is_honor_roll']) {
482 $this->assign('isHonor', TRUE);
483 $this->add('checkbox', 'pcp_display_in_roll', ts('Show my contribution in the public honor roll'), NULL, NULL,
484 ['onclick' => "showHideByValue('pcp_display_in_roll','','nameID|nickID|personalNoteID','block','radio',false); pcpAnonymous( );"]
486 $extraOption = ['onclick' => "return pcpAnonymous( );"];
488 $elements[] = &$this->createElement('radio', NULL, '', ts('Include my name and message'), 0, $extraOption);
489 $elements[] = &$this->createElement('radio', NULL, '', ts('List my contribution anonymously'), 1, $extraOption);
490 $this->addGroup($elements, 'pcp_is_anonymous', NULL, ' ');
492 $this->add('text', 'pcp_roll_nickname', ts('Name'), ['maxlength' => 30]);
493 $this->addField('pcp_personal_note', ['entity' => 'ContributionSoft', 'context' => 'create', 'style' => 'height: 3em; width: 40em;']);
496 if (empty($this->_values
['fee']) && empty($this->_ccid
)) {
497 CRM_Core_Error
::fatal(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.'));
500 //we have to load confirm contribution button in template
501 //when multiple payment processor as the user
502 //can toggle with payment processor selection
503 $billingModePaymentProcessors = 0;
504 if (!empty($this->_paymentProcessors
)) {
505 foreach ($this->_paymentProcessors
as $key => $values) {
506 if ($values['billing_mode'] == CRM_Core_Payment
::BILLING_MODE_BUTTON
) {
507 $billingModePaymentProcessors++
;
512 if ($billingModePaymentProcessors && count($this->_paymentProcessors
) == $billingModePaymentProcessors) {
513 $allAreBillingModeProcessors = TRUE;
516 $allAreBillingModeProcessors = FALSE;
519 if (!($allAreBillingModeProcessors && !$this->_values
['is_pay_later'])) {
522 'name' => CRM_Utils_Array
::value('is_confirm_enabled', $this->_values
) ?
ts('Confirm Contribution') : ts('Contribute'),
523 'spacing' => ' ',
526 // Add submit-once behavior when confirm page disabled
527 if (empty($this->_values
['is_confirm_enabled'])) {
528 $this->submitOnce
= TRUE;
530 //change button name for updating contribution
531 if (!empty($this->_ccid
)) {
532 $submitButton['name'] = ts('Confirm Payment');
534 $this->addButtons([$submitButton]);
537 $this->addFormRule(['CRM_Contribute_Form_Contribution_Main', 'formRule'], $this);
541 * Build elements to collect information for recurring contributions.
544 * @param CRM_Core_Form $form
546 public static function buildRecur(&$form) {
547 $attributes = CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_ContributionRecur');
548 $className = get_class($form);
550 $form->assign('is_recur_interval', CRM_Utils_Array
::value('is_recur_interval', $form->_values
));
551 $form->assign('is_recur_installments', CRM_Utils_Array
::value('is_recur_installments', $form->_values
));
552 $paymentObject = $form->getVar('_paymentObject');
553 if ($paymentObject) {
554 $form->assign('recurringHelpText', $paymentObject->getText('contributionPageRecurringHelp', [
555 'is_recur_installments' => !empty($form->_values
['is_recur_installments']),
556 'is_email_receipt' => !empty($form->_values
['is_email_receipt']),
560 $form->add('checkbox', 'is_recur', ts('I want to contribute this amount'), NULL);
562 if (!empty($form->_values
['is_recur_interval']) ||
$className == 'CRM_Contribute_Form_Contribution') {
563 $form->add('text', 'frequency_interval', ts('Every'), $attributes['frequency_interval'] +
['aria-label' => ts('Every')]);
564 $form->addRule('frequency_interval', ts('Frequency must be a whole number (EXAMPLE: Every 3 months).'), 'integer');
567 // make sure frequency_interval is submitted as 1 if given no choice to user.
568 $form->add('hidden', 'frequency_interval', 1);
571 $frUnits = CRM_Utils_Array
::value('recur_frequency_unit', $form->_values
);
572 if (empty($frUnits) &&
573 $className == 'CRM_Contribute_Form_Contribution'
575 $frUnits = implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
576 CRM_Core_OptionGroup
::values('recur_frequency_units')
580 $unitVals = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $frUnits);
582 // CRM 10860, display text instead of a dropdown if there's only 1 frequency unit
583 if (count($unitVals) == 1) {
584 $form->assign('one_frequency_unit', TRUE);
585 $unit = $unitVals[0];
586 $form->add('hidden', 'frequency_unit', $unit);
587 if (!empty($form->_values
['is_recur_interval']) ||
$className == 'CRM_Contribute_Form_Contribution') {
590 $form->assign('frequency_unit', $unit);
593 $form->assign('one_frequency_unit', FALSE);
595 $frequencyUnits = CRM_Core_OptionGroup
::values('recur_frequency_units', FALSE, FALSE, TRUE);
596 foreach ($unitVals as $key => $val) {
597 if (array_key_exists($val, $frequencyUnits)) {
598 $units[$val] = $frequencyUnits[$val];
599 if (!empty($form->_values
['is_recur_interval']) ||
$className == 'CRM_Contribute_Form_Contribution') {
600 $units[$val] = "{$frequencyUnits[$val]}(s)";
604 $frequencyUnit = &$form->addElement('select', 'frequency_unit', NULL, $units, ['aria-label' => ts('Frequency Unit')]);
607 // FIXME: Ideally we should freeze select box if there is only
608 // one option but looks there is some problem /w QF freeze.
609 //if ( count( $units ) == 1 ) {
610 //$frequencyUnit->freeze( );
613 $form->add('text', 'installments', ts('installments'),
614 $attributes['installments']
616 $form->addRule('installments', ts('Number of installments must be a whole number.'), 'integer');
622 * @param array $fields
623 * The input form values.
624 * @param array $files
625 * The uploaded files if any.
626 * @param \CRM_Contribute_Form_Contribution_Main $self
629 * true if no errors, else array of errors
631 public static function formRule($fields, $files, $self) {
633 $amount = self
::computeAmount($fields, $self->_values
);
634 if (CRM_Utils_Array
::value('auto_renew', $fields) &&
635 CRM_Utils_Array
::value('payment_processor_id', $fields) == 0
637 $errors['auto_renew'] = ts('You cannot have auto-renewal on if you are paying later.');
640 if ((!empty($fields['selectMembership']) &&
641 $fields['selectMembership'] != 'no_thanks'
643 (!empty($fields['priceSetId']) &&
647 $isTest = ($self->_action
& CRM_Core_Action
::PREVIEW
) ?
TRUE : FALSE;
648 $lifeMember = CRM_Member_BAO_Membership
::getAllContactMembership($self->_membershipContactID
, $isTest, TRUE);
650 $membershipOrgDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeOrganization();
653 foreach (array_keys($lifeMember) as $memTypeId) {
654 $unallowedOrgs[] = $membershipOrgDetails[$memTypeId];
658 //check for atleast one pricefields should be selected
659 if (!empty($fields['priceSetId']) && empty($self->_ccid
)) {
660 $priceField = new CRM_Price_DAO_PriceField();
661 $priceField->price_set_id
= $fields['priceSetId'];
662 $priceField->orderBy('weight');
666 $membershipIsActive = TRUE;
667 $previousId = $otherAmount = FALSE;
668 while ($priceField->fetch()) {
670 if ($self->isQuickConfig() && ($priceField->name
== 'contribution_amount' ||
$priceField->name
== 'membership_amount')) {
671 $previousId = $priceField->id
;
672 if ($priceField->name
== 'membership_amount' && !$priceField->is_active
) {
673 $membershipIsActive = FALSE;
676 if ($priceField->name
== 'other_amount') {
677 if ($self->_quickConfig
&& empty($fields["price_{$priceField->id}"]) &&
678 array_key_exists("price_{$previousId}", $fields) && isset($fields["price_{$previousId}"]) && $self->_values
['fee'][$previousId]['name'] == 'contribution_amount' && empty($fields["price_{$previousId}"])
680 $otherAmount = $priceField->id
;
682 elseif (!empty($fields["price_{$priceField->id}"])) {
683 $otherAmountVal = CRM_Utils_Rule
::cleanMoney($fields["price_{$priceField->id}"]);
684 $min = CRM_Utils_Array
::value('min_amount', $self->_values
);
685 $max = CRM_Utils_Array
::value('max_amount', $self->_values
);
686 if ($min && $otherAmountVal < $min) {
687 $errors["price_{$priceField->id}"] = ts('Contribution amount must be at least %1',
691 if ($max && $otherAmountVal > $max) {
692 $errors["price_{$priceField->id}"] = ts('Contribution amount cannot be more than %1.',
698 if (!empty($fields["price_{$priceField->id}"]) ||
($previousId == $priceField->id
&& isset($fields["price_{$previousId}"])
699 && empty($fields["price_{$previousId}"]))
701 $check[] = $priceField->id
;
705 $currentMemberships = NULL;
706 if ($membershipIsActive) {
707 $is_test = $self->_mode
!= 'live' ?
1 : 0;
708 $memContactID = $self->_membershipContactID
;
710 // For anonymous user check using dedupe rule
711 // if user has Cancelled Membership
712 if (!$memContactID) {
713 $memContactID = CRM_Contact_BAO_Contact
::getFirstDuplicateContact($fields, 'Individual', 'Unsupervised', [], FALSE);
715 $currentMemberships = CRM_Member_BAO_Membership
::getContactsCancelledMembership($memContactID,
719 foreach ($self->_values
['fee'] as $fieldKey => $fieldValue) {
720 if ($fieldValue['html_type'] != 'Text' && CRM_Utils_Array
::value('price_' . $fieldKey, $fields)) {
721 if (!is_array($fields['price_' . $fieldKey]) && isset($fieldValue['options'][$fields['price_' . $fieldKey]])) {
722 if (array_key_exists('membership_type_id', $fieldValue['options'][$fields['price_' . $fieldKey]])
723 && in_array($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'], $currentMemberships)
725 $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'])]);
729 if (is_array($fields['price_' . $fieldKey])) {
730 foreach (array_keys($fields['price_' . $fieldKey]) as $key) {
731 if (array_key_exists('membership_type_id', $fieldValue['options'][$key])
732 && in_array($fieldValue['options'][$key]['membership_type_id'], $currentMemberships)
734 $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'])]);
744 if ($membershipIsActive && !$self->_membershipBlock
['is_required']
745 && $self->_values
['amount_block_is_active']
747 $membershipFieldId = $contributionFieldId = $errorKey = $otherFieldId = NULL;
748 foreach ($self->_values
['fee'] as $fieldKey => $fieldValue) {
749 // if 'No thank you' membership is selected then set $membershipFieldId
750 if ($fieldValue['name'] == 'membership_amount' && CRM_Utils_Array
::value('price_' . $fieldKey, $fields) == 0) {
751 $membershipFieldId = $fieldKey;
753 elseif ($membershipFieldId) {
754 if ($fieldValue['name'] == 'other_amount') {
755 $otherFieldId = $fieldKey;
757 elseif ($fieldValue['name'] == 'contribution_amount') {
758 $contributionFieldId = $fieldKey;
761 if (!$errorKey || CRM_Utils_Array
::value('price_' . $contributionFieldId, $fields) == '0') {
762 $errorKey = $fieldKey;
766 // $membershipFieldId is set and additional amount is 'No thank you' or NULL then throw error
767 if ($membershipFieldId && !(CRM_Utils_Array
::value('price_' . $contributionFieldId, $fields, -1) > 0) && empty($fields['price_' . $otherFieldId])) {
768 $errors["price_{$errorKey}"] = ts('Additional Contribution is required.');
771 if (empty($check) && empty($self->_ccid
)) {
772 if ($self->_useForMember
== 1 && $membershipIsActive) {
773 $errors['_qf_default'] = ts('Select at least one option from Membership Type(s).');
776 $errors['_qf_default'] = ts('Select at least one option from Contribution(s).');
779 if ($otherAmount && !empty($check)) {
780 $errors["price_{$otherAmount}"] = ts('Amount is required field.');
783 if ($self->_useForMember
== 1 && !empty($check) && $membershipIsActive) {
785 $priceFieldMemTypes = [];
787 foreach ($self->_priceSet
['fields'] as $priceId => $value) {
788 if (!empty($fields['price_' . $priceId]) ||
($self->_quickConfig
&& $value['name'] == 'membership_amount' && empty($self->_membershipBlock
['is_required']))) {
789 if (!empty($fields['price_' . $priceId]) && is_array($fields['price_' . $priceId])) {
790 foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) {
792 $priceFieldIDS[] = $priceFldVal;
796 elseif (!$value['is_enter_qty'] && !empty($fields['price_' . $priceId])) {
797 // The check for {!$value['is_enter_qty']} is done since, quantity fields allow entering
798 // quantity. And the quantity can't be conisdered as civicrm_price_field_value.id, CRM-9577
799 $priceFieldIDS[] = $fields['price_' . $priceId];
802 if (!empty($value['options'])) {
803 foreach ($value['options'] as $val) {
804 if (!empty($val['membership_type_id']) && (
805 ($fields['price_' . $priceId] == $val['id']) ||
806 (isset($fields['price_' . $priceId]) && !empty($fields['price_' . $priceId][$val['id']]))
809 $priceFieldMemTypes[] = $val['membership_type_id'];
816 if (!empty($lifeMember)) {
817 foreach ($priceFieldIDS as $priceFieldId) {
818 if (($id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) &&
819 in_array($membershipOrgDetails[$id], $unallowedOrgs)
821 $errors['_qf_default'] = ts('You already have a lifetime membership and cannot select a membership with a shorter term.');
827 if (!empty($priceFieldIDS)) {
828 $ids = implode(',', $priceFieldIDS);
830 $priceFieldIDS['id'] = $fields['priceSetId'];
831 $self->set('memberPriceFieldIDS', $priceFieldIDS);
832 $count = CRM_Price_BAO_PriceSet
::getMembershipCount($ids);
833 foreach ($count as $id => $occurrence) {
834 if ($occurrence > 1) {
835 $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.');
840 if (empty($priceFieldMemTypes) && $self->_membershipBlock
['is_required'] == 1) {
841 $errors['_qf_default'] = ts('Please select at least one membership option.');
845 CRM_Price_BAO_PriceSet
::processAmount($self->_values
['fee'],
849 $minAmt = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $fields['priceSetId'], 'min_amount');
850 if ($fields['amount'] < 0) {
851 $errors['_qf_default'] = ts('Contribution can not be less than zero. Please select the options accordingly');
853 elseif (!empty($minAmt) && $fields['amount'] < $minAmt) {
854 $errors['_qf_default'] = ts('A minimum amount of %1 should be selected from Contribution(s).', [
855 1 => CRM_Utils_Money
::format($minAmt),
859 $amount = $fields['amount'];
862 if (isset($fields['selectProduct']) &&
863 $fields['selectProduct'] != 'no_thanks'
865 $productDAO = new CRM_Contribute_DAO_Product();
866 $productDAO->id
= $fields['selectProduct'];
867 $productDAO->find(TRUE);
868 $min_amount = $productDAO->min_contribution
;
870 if ($amount < $min_amount) {
871 $errors['selectProduct'] = ts('The premium you have selected requires a minimum contribution of %1', [1 => CRM_Utils_Money
::format($min_amount)]);
872 CRM_Core_Session
::setStatus($errors['selectProduct']);
876 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
877 CRM_Contribute_BAO_ContributionRecur
::validateRecurContribution($fields, $files, $self, $errors);
879 if (!empty($fields['is_recur']) &&
880 CRM_Utils_Array
::value('payment_processor_id', $fields) == 0
882 $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.');
885 // validate PCP fields - if not anonymous, we need a nick name value
886 if ($self->_pcpId
&& !empty($fields['pcp_display_in_roll']) &&
887 (CRM_Utils_Array
::value('pcp_is_anonymous', $fields) == 0) &&
888 CRM_Utils_Array
::value('pcp_roll_nickname', $fields) == ''
890 $errors['pcp_roll_nickname'] = ts('Please enter a name to include in the Honor Roll, or select \'contribute anonymously\'.');
893 // return if this is express mode
894 $config = CRM_Core_Config
::singleton();
895 if ($self->_paymentProcessor
&&
896 (int) $self->_paymentProcessor
['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_BUTTON
898 if (!empty($fields[$self->_expressButtonName
. '_x']) ||
!empty($fields[$self->_expressButtonName
. '_y']) ||
899 CRM_Utils_Array
::value($self->_expressButtonName
, $fields)
905 //validate the pledge fields.
906 if (!empty($self->_values
['pledge_block_id'])) {
907 //validation for pledge payment.
908 if (!empty($self->_values
['pledge_id'])) {
909 if (empty($fields['pledge_amount'])) {
910 $errors['pledge_amount'] = ts('At least one payment option needs to be checked.');
913 elseif (!empty($fields['is_pledge'])) {
914 if (CRM_Utils_Rule
::positiveInteger(CRM_Utils_Array
::value('pledge_installments', $fields)) == FALSE) {
915 $errors['pledge_installments'] = ts('Please enter a valid number of pledge installments.');
918 if (CRM_Utils_Array
::value('pledge_installments', $fields) == NULL) {
919 $errors['pledge_installments'] = ts('Pledge Installments is required field.');
921 elseif (CRM_Utils_Array
::value('pledge_installments', $fields) == 1) {
922 $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.');
924 elseif (CRM_Utils_Array
::value('pledge_installments', $fields) == 0) {
925 $errors['pledge_installments'] = ts('Pledge Installments field must be > 1.');
929 //validation for Pledge Frequency Interval.
930 if (CRM_Utils_Rule
::positiveInteger(CRM_Utils_Array
::value('pledge_frequency_interval', $fields)) == FALSE) {
931 $errors['pledge_frequency_interval'] = ts('Please enter a valid Pledge Frequency Interval.');
934 if (CRM_Utils_Array
::value('pledge_frequency_interval', $fields) == NULL) {
935 $errors['pledge_frequency_interval'] = ts('Pledge Frequency Interval. is required field.');
937 elseif (CRM_Utils_Array
::value('pledge_frequency_interval', $fields) == 0) {
938 $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0');
944 // if the user has chosen a free membership or the amount is less than zero
945 // i.e. we don't need to validate payment related fields or profiles.
946 if ((float) $amount <= 0.0) {
950 if (CRM_Utils_Array
::value('payment_processor_id', $fields) === NULL) {
951 $errors['payment_processor_id'] = ts('Payment Method is a required field.');
954 CRM_Core_Payment_Form
::validatePaymentInstrument(
955 $fields['payment_processor_id'],
958 (!$self->_isBillingAddressRequiredForPayLater ?
NULL : 'billing')
962 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
963 if ($greetingType = CRM_Utils_Array
::value($greeting, $fields)) {
964 $customizedValue = CRM_Core_PseudoConstant
::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
965 if ($customizedValue == $greetingType && empty($fielse[$greeting . '_custom'])) {
966 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
967 [1 => ucwords(str_replace('_', " ", $greeting))]
973 return empty($errors) ?
TRUE : $errors;
977 * Compute amount to be paid.
979 * @param array $params
980 * @param array $formValues
982 * @return int|mixed|null|string
984 public static function computeAmount($params, $formValues) {
986 // First clean up the other amount field if present.
987 if (isset($params['amount_other'])) {
988 $params['amount_other'] = CRM_Utils_Rule
::cleanMoney($params['amount_other']);
991 if (CRM_Utils_Array
::value('amount', $params) == 'amount_other_radio' ||
!empty($params['amount_other'])) {
992 $amount = $params['amount_other'];
994 elseif (!empty($params['pledge_amount'])) {
995 foreach ($params['pledge_amount'] as $paymentId => $dontCare) {
996 $amount +
= CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount');
1000 if (!empty($formValues['amount'])) {
1001 $amountID = CRM_Utils_Array
::value('amount', $params);
1004 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1005 // function to get correct amount level consistently. Remove setting of the amount level in
1006 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1007 // to cover all variants.
1008 $params['amount_level'] = CRM_Utils_Array
::value('label', $formValues[$amountID]);
1009 $amount = CRM_Utils_Array
::value('value', $formValues[$amountID]);
1017 * Process the form submission.
1019 public function postProcess() {
1020 // we first reset the confirm page so it accepts new values
1021 $this->controller
->resetPage('Confirm');
1023 // get the submitted form values.
1024 $params = $this->controller
->exportValues($this->_name
);
1025 $this->submit($params);
1027 if (empty($this->_values
['is_confirm_enabled'])) {
1028 $this->skipToThankYouPage();
1036 * This is the guts of the postProcess made also accessible to the test suite.
1038 * @param array $params
1041 public function submit($params) {
1042 //carry campaign from profile.
1043 if (array_key_exists('contribution_campaign_id', $params)) {
1044 $params['campaign_id'] = $params['contribution_campaign_id'];
1047 $params['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
1049 // @todo refactor this & leverage it from the unit tests.
1050 if (!empty($params['priceSetId'])) {
1051 $is_quick_config = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config');
1052 if ($is_quick_config) {
1053 $priceField = new CRM_Price_DAO_PriceField();
1054 $priceField->price_set_id
= $params['priceSetId'];
1055 $priceField->orderBy('weight');
1056 $priceField->find();
1059 while ($priceField->fetch()) {
1060 CRM_Price_BAO_PriceFieldValue
::getValues($priceField->id
, $priceOptions);
1061 if (($selectedPriceOptionID = CRM_Utils_Array
::value("price_{$priceField->id}", $params)) != FALSE && $selectedPriceOptionID > 0) {
1062 switch ($priceField->name
) {
1063 case 'membership_amount':
1064 $this->_params
['selectMembership'] = $params['selectMembership'] = CRM_Utils_Array
::value('membership_type_id', $priceOptions[$selectedPriceOptionID]);
1065 $this->set('selectMembership', $params['selectMembership']);
1067 case 'contribution_amount':
1068 $params['amount'] = $selectedPriceOptionID;
1069 if ($priceField->name
== 'contribution_amount' ||
1070 ($priceField->name
== 'membership_amount' &&
1071 CRM_Utils_Array
::value('is_separate_payment', $this->_membershipBlock
) == 0)
1073 $this->_values
['amount'] = CRM_Utils_Array
::value('amount', $priceOptions[$selectedPriceOptionID]);
1075 $this->_values
[$selectedPriceOptionID]['value'] = CRM_Utils_Array
::value('amount', $priceOptions[$selectedPriceOptionID]);
1076 $this->_values
[$selectedPriceOptionID]['label'] = CRM_Utils_Array
::value('label', $priceOptions[$selectedPriceOptionID]);
1077 $this->_values
[$selectedPriceOptionID]['amount_id'] = CRM_Utils_Array
::value('id', $priceOptions[$selectedPriceOptionID]);
1078 $this->_values
[$selectedPriceOptionID]['weight'] = CRM_Utils_Array
::value('weight', $priceOptions[$selectedPriceOptionID]);
1081 case 'other_amount':
1082 $params['amount_other'] = $selectedPriceOptionID;
1090 if (!empty($this->_ccid
) && !empty($this->_pendingAmount
)) {
1091 $params['amount'] = $this->_pendingAmount
;
1094 // from here on down, $params['amount'] holds a monetary value (or null) rather than an option ID
1095 $params['amount'] = self
::computeAmount($params, $this->_values
);
1098 $params['separate_amount'] = $params['amount'];
1100 if (!empty($params['selectMembership'])) {
1101 if (empty($this->_membershipTypeValues
)) {
1102 $this->_membershipTypeValues
= CRM_Member_BAO_Membership
::buildMembershipTypeValues($this,
1103 (array) $params['selectMembership']
1106 $membershipTypeValues = $this->_membershipTypeValues
[$params['selectMembership']];
1107 $memFee = $membershipTypeValues['minimum_fee'];
1108 if (!$params['amount'] && !$this->_separateMembershipPayment
) {
1109 $params['amount'] = $memFee ?
$memFee : 0;
1112 //If the membership & contribution is used in contribution page & not separate payment
1113 $memPresent = $membershipLabel = $fieldOption = $is_quick_config = NULL;
1114 $proceFieldAmount = 0;
1115 if (property_exists($this, '_separateMembershipPayment') && $this->_separateMembershipPayment
== 0) {
1116 $is_quick_config = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config');
1117 if ($is_quick_config) {
1118 foreach ($this->_priceSet
['fields'] as $fieldKey => $fieldVal) {
1119 if ($fieldVal['name'] == 'membership_amount' && !empty($params['price_' . $fieldKey])) {
1120 $fieldId = $fieldVal['id'];
1121 $fieldOption = $params['price_' . $fieldId];
1122 $proceFieldAmount +
= $fieldVal['options'][$this->_submitValues
['price_' . $fieldId]]['amount'];
1126 if (!empty($params['price_' . $fieldKey]) && $memPresent && ($fieldVal['name'] == 'other_amount' ||
$fieldVal['name'] == 'contribution_amount')) {
1127 $fieldId = $fieldVal['id'];
1128 if ($fieldVal['name'] == 'other_amount') {
1129 $proceFieldAmount +
= $this->_submitValues
['price_' . $fieldId];
1131 elseif ($fieldVal['name'] == 'contribution_amount' && $this->_submitValues
['price_' . $fieldId] > 0) {
1132 $proceFieldAmount +
= $fieldVal['options'][$this->_submitValues
['price_' . $fieldId]]['amount'];
1134 unset($params['price_' . $fieldId]);
1142 if (!isset($params['amount_other'])) {
1143 $this->set('amount_level', CRM_Utils_Array
::value('amount_level', $params));
1146 if (!empty($this->_ccid
)) {
1147 $this->set('lineItem', $this->_lineItem
);
1149 elseif ($priceSetId = CRM_Utils_Array
::value('priceSetId', $params)) {
1151 $is_quick_config = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1152 if ($is_quick_config) {
1153 foreach ($this->_values
['fee'] as $key => & $val) {
1154 if ($val['name'] == 'other_amount' && $val['html_type'] == 'Text' && !empty($params['price_' . $key])) {
1155 // Clean out any currency symbols.
1156 $params['price_' . $key] = CRM_Utils_Rule
::cleanMoney($params['price_' . $key]);
1157 if ($params['price_' . $key] != 0) {
1158 foreach ($val['options'] as $optionKey => & $options) {
1159 $options['amount'] = CRM_Utils_Array
::value('price_' . $key, $params);
1163 $params['price_' . $key] = 1;
1169 if ($this->_membershipBlock
) {
1170 $component = 'membership';
1173 CRM_Price_BAO_PriceSet
::processAmount($this->_values
['fee'], $params, $lineItem[$priceSetId], $component, $priceSetId);
1174 if ($params['tax_amount']) {
1175 $this->set('tax_amount', $params['tax_amount']);
1178 if ($proceFieldAmount) {
1179 $lineItem[$params['priceSetId']][$fieldOption]['unit_price'] = $proceFieldAmount;
1180 $lineItem[$params['priceSetId']][$fieldOption]['line_total'] = $proceFieldAmount;
1181 if (isset($lineItem[$params['priceSetId']][$fieldOption]['tax_amount'])) {
1182 $proceFieldAmount +
= $lineItem[$params['priceSetId']][$fieldOption]['tax_amount'];
1184 if (!$this->_membershipBlock
['is_separate_payment']) {
1185 //require when separate membership not used
1186 $params['amount'] = $proceFieldAmount;
1189 $this->set('lineItem', $lineItem);
1192 if ($params['amount'] != 0 && (($this->_values
['is_pay_later'] &&
1193 empty($this->_paymentProcessor
) &&
1194 !array_key_exists('hidden_processor', $params)) ||
1195 (CRM_Utils_Array
::value('payment_processor_id', $params) == 0))
1197 $params['is_pay_later'] = 1;
1200 $params['is_pay_later'] = 0;
1203 // Would be nice to someday understand the point of this set.
1204 $this->set('is_pay_later', $params['is_pay_later']);
1205 // assign pay later stuff
1206 $this->_params
['is_pay_later'] = CRM_Utils_Array
::value('is_pay_later', $params, FALSE);
1207 $this->assign('is_pay_later', $params['is_pay_later']);
1208 if ($params['is_pay_later']) {
1209 $this->assign('pay_later_text', $this->_values
['pay_later_text']);
1210 $this->assign('pay_later_receipt', CRM_Utils_Array
::value('pay_later_receipt', $this->_values
));
1213 if ($this->_membershipBlock
['is_separate_payment'] && !empty($params['separate_amount'])) {
1214 $this->set('amount', $params['separate_amount']);
1217 $this->set('amount', $params['amount']);
1220 // generate and set an invoiceID for this transaction
1221 $invoiceID = md5(uniqid(rand(), TRUE));
1222 $this->set('invoiceID', $invoiceID);
1223 $params['invoiceID'] = $invoiceID;
1224 $params['description'] = ts('Online Contribution') . ': ' . ((!empty($this->_pcpInfo
['title']) ?
$this->_pcpInfo
['title'] : $this->_values
['title']));
1225 $params['button'] = $this->controller
->getButtonName();
1226 // required only if is_monetary and valid positive amount
1227 // @todo it seems impossible for $memFee to be greater than 0 & $params['amount'] not to
1228 // be & by requiring $memFee down here we make it harder to do a sensible refactoring of the function
1229 // above (ie. extract the amount in a small function).
1230 if ($this->_values
['is_monetary'] &&
1231 !empty($this->_paymentProcessor
) &&
1232 ((float ) $params['amount'] > 0.0 ||
$memFee > 0.0)
1234 // The concept of contributeMode is deprecated - as should be the 'is_monetary' setting.
1235 $this->setContributeMode();
1236 // Really this setting of $this->_params & params within it should be done earlier on in the function
1237 // probably the values determined here should be reused in confirm postProcess as there is no opportunity to alter anything
1238 // on the confirm page. However as we are dealing with a stable release we go as close to where it is used
1240 // In general the form has a lack of clarity of the logic of why things are set on the form in some cases &
1241 // the logic around when $this->_params is used compared to other params arrays.
1242 $this->_params
= array_merge($params, $this->_params
);
1243 $this->setRecurringMembershipParams();
1244 if ($this->_paymentProcessor
&&
1245 $this->_paymentProcessor
['object']->supports('preApproval')
1247 $this->handlePreApproval($this->_params
);
1253 * Assign the billing mode to the template.
1255 * This is required for legacy support for contributeMode in templates.
1257 * The goal is to remove this parameter & use more relevant parameters.
1259 protected function setContributeMode() {
1260 switch ($this->_paymentProcessor
['billing_mode']) {
1261 case CRM_Core_Payment
::BILLING_MODE_FORM
:
1262 $this->set('contributeMode', 'direct');
1265 case CRM_Core_Payment
::BILLING_MODE_BUTTON
:
1266 $this->set('contributeMode', 'express');
1269 case CRM_Core_Payment
::BILLING_MODE_NOTIFY
:
1270 $this->set('contributeMode', 'notify');
1277 * Process confirm function and pass browser to the thank you page.
1279 protected function skipToThankYouPage() {
1280 // call the post process hook for the main page before we switch to confirm
1281 $this->postProcessHook();
1283 // build the confirm page
1284 $confirmForm = &$this->controller
->_pages
['Confirm'];
1285 $confirmForm->preProcess();
1286 $confirmForm->buildQuickForm();
1288 // the confirmation page is valid
1289 $data = &$this->controller
->container();
1290 $data['valid']['Confirm'] = 1;
1292 // confirm the contribution
1293 // mainProcess calls the hook also
1294 $confirmForm->mainProcess();
1295 $qfKey = $this->controller
->_key
;
1297 // redirect to thank you page
1298 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_ThankYou_display=1&qfKey=$qfKey", TRUE, NULL, FALSE));
1302 * Set form variables if contribution ID is found
1304 public function assignFormVariablesByContributionID() {
1305 if (empty($this->_ccid
)) {
1308 if (!$this->getContactID()) {
1309 CRM_Core_Error
::statusBounce(ts("Returning since there is no contact attached to this contribution id."));
1312 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($this->_ccid
);
1313 //bounce if the contribution is not pending.
1314 if ((int) $paymentBalance <= 0) {
1315 CRM_Core_Error
::statusBounce(ts("Returning since contribution has already been handled."));
1317 if (!empty($paymentBalance)) {
1318 $this->_pendingAmount
= $paymentBalance;
1319 $this->assign('pendingAmount', $this->_pendingAmount
);
1322 if ($taxAmount = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_ccid
, 'tax_amount')) {
1323 $this->set('tax_amount', $taxAmount);
1324 $this->assign('taxAmount', $taxAmount);
1327 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->_ccid
);
1328 foreach (array_keys($lineItems) as $id) {
1329 $lineItems[$id]['id'] = $id;
1331 $itemId = key($lineItems);
1332 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1333 $this->_priceSetId
= CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1336 if (!empty($lineItems[$itemId]['price_field_id'])) {
1337 $this->_lineItem
[$this->_priceSetId
] = $lineItems;
1339 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config');
1340 $this->assign('lineItem', $this->_lineItem
);
1341 $this->assign('is_quick_config', $isQuickConfig);
1342 $this->assign('priceSetID', $this->_priceSetId
);
1346 * Function for unit tests on the postProcess function.
1348 * @param array $params
1350 public function testSubmit($params) {
1351 $_SERVER['REQUEST_METHOD'] = 'GET';
1352 $this->controller
= new CRM_Contribute_Controller_Contribution();
1353 $this->submit($params);