Merge pull request #23041 from christianwach/lab-core-2103
[civicrm-core.git] / CRM / Contribute / Form / Contribution / Main.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class generates form components for processing a Contribution.
20 */
21 class CRM_Contribute_Form_Contribution_Main extends CRM_Contribute_Form_ContributionBase {
22
23 /**
24 * Define default MembershipType Id.
25 * @var int
26 */
27 public $_defaultMemTypeId;
28
29 public $_paymentProcessors;
30
31 public $_membershipTypeValues;
32
33 public $_useForMember;
34
35 /**
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
37 * @var array
38 */
39 public $_paymentFields = [];
40
41 protected $_paymentProcessorID;
42 protected $_snippet;
43
44 /**
45 * Get the active UFGroups (profiles) on this form
46 * Many forms load one or more UFGroups (profiles).
47 * This provides a standard function to retrieve the IDs of those profiles from the form
48 * so that you can implement things such as "is is_captcha field set on any of the active profiles on this form?"
49 *
50 * NOT SUPPORTED FOR USE OUTSIDE CORE EXTENSIONS - Added for reCAPTCHA core extension.
51 *
52 * @return array
53 */
54 public function getUFGroupIDs() {
55 $ufGroupIDs = [];
56 if (!empty($this->_values['custom_pre_id'])) {
57 $ufGroupIDs[] = $this->_values['custom_pre_id'];
58 }
59 if (!empty($this->_values['custom_post_id'])) {
60 // custom_post_id can be an array (because we can have multiple for events).
61 // It is handled as array for contribution page as well though they don't support multiple profiles.
62 if (!is_array($this->_values['custom_post_id'])) {
63 $ufGroupIDs[] = $this->_values['custom_post_id'];
64 }
65 else {
66 $ufGroupIDs = array_merge($ufGroupIDs, $this->_values['custom_post_id']);
67 }
68 }
69
70 return $ufGroupIDs;
71 }
72
73 /**
74 * Set variables up before form is built.
75 */
76 public function preProcess() {
77 parent::preProcess();
78
79 $this->_paymentProcessors = $this->get('paymentProcessors');
80 $this->preProcessPaymentOptions();
81
82 $this->assignFormVariablesByContributionID();
83
84 // Make the contributionPageID available to the template
85 $this->assign('contributionPageID', $this->_id);
86 $this->assign('ccid', $this->_ccid);
87 $this->assign('isShare', CRM_Utils_Array::value('is_share', $this->_values));
88 $this->assign('isConfirmEnabled', CRM_Utils_Array::value('is_confirm_enabled', $this->_values));
89
90 // Required for currency formatting in the JS layer
91 // this is a temporary fix intended to resolve a regression quickly
92 // And assigning moneyFormat for js layer formatting
93 // will only work until that is done.
94 // https://github.com/civicrm/civicrm-core/pull/19151
95 $this->assign('moneyFormat', CRM_Utils_Money::format(1234.56));
96
97 $this->assign('reset', CRM_Utils_Request::retrieve('reset', 'Boolean'));
98 $this->assign('mainDisplay', CRM_Utils_Request::retrieve('_qf_Main_display', 'Boolean',
99 CRM_Core_DAO::$_nullObject));
100
101 if (!empty($this->_pcpInfo['id']) && !empty($this->_pcpInfo['intro_text'])) {
102 $this->assign('intro_text', $this->_pcpInfo['intro_text']);
103 }
104 elseif (!empty($this->_values['intro_text'])) {
105 $this->assign('intro_text', $this->_values['intro_text']);
106 }
107
108 $qParams = "reset=1&amp;id={$this->_id}";
109 if ($pcpId = CRM_Utils_Array::value('pcp_id', $this->_pcpInfo)) {
110 $qParams .= "&amp;pcpId={$pcpId}";
111 }
112 $this->assign('qParams', $qParams);
113
114 if (!empty($this->_values['footer_text'])) {
115 $this->assign('footer_text', $this->_values['footer_text']);
116 }
117 }
118
119 /**
120 * Set the default values.
121 */
122 public function setDefaultValues() {
123 // check if the user is registered and we have a contact ID
124 $contactID = $this->getContactID();
125
126 if (!empty($contactID)) {
127 $fields = [];
128 $removeCustomFieldTypes = ['Contribution', 'Membership'];
129 $contribFields = CRM_Contribute_BAO_Contribution::getContributionFields();
130
131 // remove component related fields
132 foreach ($this->_fields as $name => $fieldInfo) {
133 //don't set custom data Used for Contribution (CRM-1344)
134 if (substr($name, 0, 7) == 'custom_') {
135 $id = substr($name, 7);
136 if (!CRM_Core_BAO_CustomGroup::checkCustomField($id, $removeCustomFieldTypes)) {
137 continue;
138 }
139 // ignore component fields
140 }
141 elseif (array_key_exists($name, $contribFields) || (substr($name, 0, 11) == 'membership_') || (substr($name, 0, 13) == 'contribution_')) {
142 continue;
143 }
144 $fields[$name] = $fieldInfo;
145 }
146
147 if (!empty($fields)) {
148 CRM_Core_BAO_UFGroup::setProfileDefaults($contactID, $fields, $this->_defaults);
149 }
150
151 $billingDefaults = $this->getProfileDefaults('Billing', $contactID);
152 $this->_defaults = array_merge($this->_defaults, $billingDefaults);
153 }
154 if (!empty($this->_ccid) && !empty($this->_pendingAmount)) {
155 $this->_defaults['total_amount'] = CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($this->_pendingAmount);
156 }
157
158 /*
159 * hack to simplify credit card entry for testing
160 *
161 * $this->_defaults['credit_card_type'] = 'Visa';
162 * $this->_defaults['amount'] = 168;
163 * $this->_defaults['credit_card_number'] = '4111111111111111';
164 * $this->_defaults['cvv2'] = '000';
165 * $this->_defaults['credit_card_exp_date'] = array('Y' => date('Y')+1, 'M' => '05');
166 * // hack to simplify direct debit entry for testing
167 * $this->_defaults['account_holder'] = 'Max Müller';
168 * $this->_defaults['bank_account_number'] = '12345678';
169 * $this->_defaults['bank_identification_number'] = '12030000';
170 * $this->_defaults['bank_name'] = 'Bankname';
171 */
172
173 //build set default for pledge overdue payment.
174 if (!empty($this->_values['pledge_id'])) {
175 //used to record completed pledge payment ids used later for honor default
176 $completedContributionIds = [];
177 $pledgePayments = CRM_Pledge_BAO_PledgePayment::getPledgePayments($this->_values['pledge_id']);
178
179 $paymentAmount = 0;
180 $duePayment = FALSE;
181 foreach ($pledgePayments as $payId => $value) {
182 if ($value['status'] == 'Overdue') {
183 $this->_defaults['pledge_amount'][$payId] = 1;
184 $paymentAmount += $value['scheduled_amount'];
185 }
186 elseif (!$duePayment && $value['status'] == 'Pending') {
187 $this->_defaults['pledge_amount'][$payId] = 1;
188 $paymentAmount += $value['scheduled_amount'];
189 $duePayment = TRUE;
190 }
191 elseif ($value['status'] == 'Completed' && $value['contribution_id']) {
192 $completedContributionIds[] = $value['contribution_id'];
193 }
194 }
195 $this->_defaults['price_' . $this->_priceSetId] = $paymentAmount;
196
197 if (count($completedContributionIds)) {
198 $softCredit = [];
199 foreach ($completedContributionIds as $id) {
200 $softCredit = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($id);
201 }
202 if (isset($softCredit['soft_credit'])) {
203 $this->_defaults['soft_credit_type_id'] = $softCredit['soft_credit'][1]['soft_credit_type'];
204
205 //since honoree profile fieldname of fields are prefixed with 'honor'
206 //we need to reformat the fieldname to append prefix during setting default values
207 CRM_Core_BAO_UFGroup::setProfileDefaults(
208 $softCredit['soft_credit'][1]['contact_id'],
209 CRM_Core_BAO_UFGroup::getFields($this->_honoreeProfileId),
210 $defaults
211 );
212 foreach ($defaults as $fieldName => $value) {
213 $this->_defaults['honor[' . $fieldName . ']'] = $value;
214 }
215 }
216 }
217 }
218 elseif (!empty($this->_values['pledge_block_id'])) {
219 //set default to one time contribution.
220 $this->_defaults['is_pledge'] = 0;
221 }
222
223 // to process Custom data that are appended to URL
224 $getDefaults = CRM_Core_BAO_CustomGroup::extractGetParams($this, "'Contact', 'Individual', 'Contribution'");
225 $this->_defaults = array_merge($this->_defaults, $getDefaults);
226
227 $config = CRM_Core_Config::singleton();
228 // set default country from config if no country set
229 if (empty($this->_defaults["billing_country_id-{$this->_bltID}"])) {
230 $this->_defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
231 }
232
233 // set default state/province from config if no state/province set
234 if (empty($this->_defaults["billing_state_province_id-{$this->_bltID}"])) {
235 $this->_defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
236 }
237
238 $entityId = $memtypeID = NULL;
239 if ($this->_priceSetId) {
240 if (($this->_useForMember && !empty($this->_currentMemberships)) || $this->_defaultMemTypeId) {
241 $selectedCurrentMemTypes = [];
242 foreach ($this->_priceSet['fields'] as $key => $val) {
243 foreach ($val['options'] as $keys => $values) {
244 $opMemTypeId = $values['membership_type_id'] ?? NULL;
245 $priceFieldName = 'price_' . $values['price_field_id'];
246 $priceFieldValue = CRM_Price_BAO_PriceSet::getPriceFieldValueFromURL($this, $priceFieldName);
247 if (!empty($priceFieldValue)) {
248 CRM_Price_BAO_PriceSet::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $this->_defaults);
249 // break here to prevent overwriting of default due to 'is_default'
250 // option configuration or setting of current membership or
251 // membership for related organization.
252 // The value sent via URL get's higher priority.
253 break;
254 }
255 elseif ($opMemTypeId &&
256 in_array($opMemTypeId, $this->_currentMemberships) &&
257 !in_array($opMemTypeId, $selectedCurrentMemTypes)
258 ) {
259 CRM_Price_BAO_PriceSet::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $this->_defaults);
260 $memtypeID = $selectedCurrentMemTypes[] = $values['membership_type_id'];
261 }
262 elseif (!empty($values['is_default']) && !$opMemTypeId && (!isset($this->_defaults[$priceFieldName]) ||
263 ($val['html_type'] == 'CheckBox' && !isset($this->_defaults[$priceFieldName][$keys])))) {
264 CRM_Price_BAO_PriceSet::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $this->_defaults);
265 $memtypeID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $this->_defaults[$priceFieldName], 'membership_type_id');
266 }
267 }
268 }
269 $entityId = CRM_Utils_Array::value('id', CRM_Member_BAO_Membership::getContactMembership($contactID, $memtypeID, NULL));
270 }
271 else {
272 CRM_Price_BAO_PriceSet::setDefaultPriceSet($this, $this->_defaults);
273 }
274 }
275
276 //set custom field defaults set by admin if value is not set
277 if (!empty($this->_fields)) {
278 //load default campaign from page.
279 if (array_key_exists('contribution_campaign_id', $this->_fields)) {
280 $this->_defaults['contribution_campaign_id'] = $this->_values['campaign_id'] ?? NULL;
281 }
282
283 //set custom field defaults
284 foreach ($this->_fields as $name => $field) {
285 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
286 if (!isset($this->_defaults[$name])) {
287 CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $this->_defaults,
288 $entityId, CRM_Profile_Form::MODE_REGISTER
289 );
290 }
291 }
292 }
293 }
294
295 if (!empty($this->_paymentProcessors)) {
296 foreach ($this->_paymentProcessors as $pid => $value) {
297 if (!empty($value['is_default'])) {
298 $this->_defaults['payment_processor_id'] = $pid;
299 }
300 }
301 }
302
303 return $this->_defaults;
304 }
305
306 /**
307 * Build the form object.
308 */
309 public function buildQuickForm() {
310 // build profiles first so that we can determine address fields etc
311 // and then show copy address checkbox
312 if (empty($this->_ccid)) {
313 $this->buildCustom($this->_values['custom_pre_id'], 'customPre');
314 $this->buildCustom($this->_values['custom_post_id'], 'customPost');
315
316 // CRM-18399: used by template to pass pre profile id as a url arg
317 $this->assign('custom_pre_id', $this->_values['custom_pre_id']);
318
319 $this->buildComponentForm($this->_id, $this);
320 }
321
322 if (\Civi::settings()->get('forceRecaptcha')) {
323 if (!$this->_userID) {
324 CRM_Utils_ReCAPTCHA::enableCaptchaOnForm($this);
325 }
326 }
327
328 // Build payment processor form
329 CRM_Core_Payment_ProcessorForm::buildQuickForm($this);
330
331 $config = CRM_Core_Config::singleton();
332
333 $contactID = $this->getContactID();
334 if ($contactID) {
335 $this->assign('contact_id', $contactID);
336 $this->assign('display_name', CRM_Contact_BAO_Contact::displayName($contactID));
337 }
338
339 $this->applyFilter('__ALL__', 'trim');
340 if (empty($this->_ccid)) {
341 if ($this->_emailExists == FALSE) {
342 $this->add('text', "email-{$this->_bltID}",
343 ts('Email Address'),
344 ['size' => 30, 'maxlength' => 60, 'class' => 'email'],
345 TRUE
346 );
347 $this->assign('showMainEmail', TRUE);
348 $this->addRule("email-{$this->_bltID}", ts('Email is not valid.'), 'email');
349 }
350 }
351 else {
352 $this->addElement('hidden', "email-{$this->_bltID}", 1);
353 $this->add('text', 'total_amount', ts('Total Amount'), ['readonly' => TRUE], FALSE);
354 }
355 $pps = $this->getProcessors();
356 $this->addPaymentProcessorFieldsToForm();
357 if (!empty($pps) && count($pps) === 1) {
358 $ppKeys = array_keys($pps);
359 $currentPP = array_pop($ppKeys);
360 if ($currentPP === 0) {
361 $this->assign('is_pay_later', $this->_values['is_pay_later']);
362 $this->assign('pay_later_text', $this->getPayLaterLabel());
363 }
364 }
365
366 if ($contactID === 0) {
367 $this->addCidZeroOptions();
368 }
369
370 //build pledge block.
371 $this->_useForMember = 0;
372 //don't build membership block when pledge_id is passed
373 if (empty($this->_values['pledge_id']) && empty($this->_ccid)) {
374 $this->_separateMembershipPayment = FALSE;
375 if (CRM_Core_Component::isEnabled('CiviMember')) {
376 $isTest = 0;
377 if ($this->_action & CRM_Core_Action::PREVIEW) {
378 $isTest = 1;
379 }
380
381 if ($this->_priceSetId &&
382 (CRM_Core_Component::getComponentID('CiviMember') == CRM_Utils_Array::value('extends', $this->_priceSet))
383 ) {
384 $this->_useForMember = 1;
385 $this->set('useForMember', $this->_useForMember);
386 }
387
388 $this->_separateMembershipPayment = $this->buildMembershipBlock(
389 $this->_membershipContactID,
390 NULL,
391 $isTest
392 );
393 }
394 $this->set('separateMembershipPayment', $this->_separateMembershipPayment);
395 }
396 $this->assign('useForMember', $this->_useForMember);
397 // If we configured price set for contribution page
398 // we are not allow membership signup as well as any
399 // other contribution amount field, CRM-5095
400 if (!empty($this->_priceSetId)) {
401 $this->add('hidden', 'priceSetId', $this->_priceSetId);
402 // build price set form.
403 $this->set('priceSetId', $this->_priceSetId);
404 if (empty($this->_ccid)) {
405 CRM_Price_BAO_PriceSet::buildPriceSet($this);
406 }
407 if ($this->_values['is_monetary'] &&
408 $this->_values['is_recur'] && empty($this->_values['pledge_id'])
409 ) {
410 self::buildRecur($this);
411 }
412 }
413
414 if ($this->_priceSetId && empty($this->_ccid)) {
415 $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
416 if ($is_quick_config) {
417 $this->_useForMember = 0;
418 $this->set('useForMember', $this->_useForMember);
419 }
420 }
421
422 //we allow premium for pledge during pledge creation only.
423 if (empty($this->_values['pledge_id']) && empty($this->_ccid)) {
424 CRM_Contribute_BAO_Premium::buildPremiumBlock($this, $this->_id, TRUE);
425 }
426
427 //don't build pledge block when mid is passed
428 if (!$this->_mid && empty($this->_ccid)) {
429 if (CRM_Core_Component::isEnabled('CiviPledge') && !empty($this->_values['pledge_block_id'])) {
430 CRM_Pledge_BAO_PledgeBlock::buildPledgeBlock($this);
431 }
432 }
433
434 //to create an cms user
435 if (!$this->_contactID && empty($this->_ccid)) {
436 $createCMSUser = FALSE;
437
438 if ($this->_values['custom_pre_id']) {
439 $profileID = $this->_values['custom_pre_id'];
440 $createCMSUser = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_cms_user');
441 }
442
443 if (!$createCMSUser &&
444 $this->_values['custom_post_id']
445 ) {
446 if (!is_array($this->_values['custom_post_id'])) {
447 $profileIDs = [$this->_values['custom_post_id']];
448 }
449 else {
450 $profileIDs = $this->_values['custom_post_id'];
451 }
452 foreach ($profileIDs as $pid) {
453 if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $pid, 'is_cms_user')) {
454 $profileID = $pid;
455 $createCMSUser = TRUE;
456 break;
457 }
458 }
459 }
460
461 if ($createCMSUser) {
462 CRM_Core_BAO_CMSUser::buildForm($this, $profileID, TRUE);
463 }
464 }
465 if ($this->_pcpId && empty($this->_ccid)) {
466 if (CRM_PCP_BAO_PCP::displayName($this->_pcpId)) {
467 $pcp_supporter_text = CRM_PCP_BAO_PCP::getPcpSupporterText($this->_pcpId, $this->_id, 'contribute');
468 $this->assign('pcpSupporterText', $pcp_supporter_text);
469 }
470 $prms = ['id' => $this->_pcpId];
471 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $prms, $pcpInfo);
472 if ($pcpInfo['is_honor_roll']) {
473 $this->assign('isHonor', TRUE);
474 $this->add('checkbox', 'pcp_display_in_roll', ts('Show my contribution in the public honor roll'), NULL, NULL,
475 ['onclick' => "showHideByValue('pcp_display_in_roll','','nameID|nickID|personalNoteID','block','radio',false); pcpAnonymous( );"]
476 );
477 $extraOption = ['onclick' => "return pcpAnonymous( );"];
478 $this->addRadio('pcp_is_anonymous', NULL, [ts('Include my name and message'), ts('List my contribution anonymously')], [], '&nbsp;&nbsp;&nbsp;', FALSE, [$extraOption, $extraOption]);
479
480 $this->add('text', 'pcp_roll_nickname', ts('Name'), ['maxlength' => 30]);
481 $this->addField('pcp_personal_note', ['entity' => 'ContributionSoft', 'context' => 'create', 'style' => 'height: 3em; width: 40em;']);
482 }
483 }
484 if (empty($this->_values['fee']) && empty($this->_ccid)) {
485 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.'));
486 }
487
488 //we have to load confirm contribution button in template
489 //when multiple payment processor as the user
490 //can toggle with payment processor selection
491 $billingModePaymentProcessors = 0;
492 if (!empty($this->_paymentProcessors)) {
493 foreach ($this->_paymentProcessors as $key => $values) {
494 if ($values['billing_mode'] == CRM_Core_Payment::BILLING_MODE_BUTTON) {
495 $billingModePaymentProcessors++;
496 }
497 }
498 }
499
500 if ($billingModePaymentProcessors && count($this->_paymentProcessors) == $billingModePaymentProcessors) {
501 $allAreBillingModeProcessors = TRUE;
502 }
503 else {
504 $allAreBillingModeProcessors = FALSE;
505 }
506
507 if (!($allAreBillingModeProcessors && !$this->_values['is_pay_later'])) {
508 $submitButton = [
509 'type' => 'upload',
510 'name' => ts('Contribute'),
511 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
512 'isDefault' => TRUE,
513 ];
514 if (!empty($this->_values['is_confirm_enabled'])) {
515 $submitButton['name'] = ts('Review your contribution');
516 $submitButton['icon'] = 'fa-chevron-right';
517 }
518 // Add submit-once behavior when confirm page disabled
519 if (empty($this->_values['is_confirm_enabled'])) {
520 $this->submitOnce = TRUE;
521 }
522 //change button name for updating contribution
523 if (!empty($this->_ccid)) {
524 $submitButton['name'] = ts('Confirm Payment');
525 }
526 $this->addButtons([$submitButton]);
527 }
528
529 $this->addFormRule(['CRM_Contribute_Form_Contribution_Main', 'formRule'], $this);
530 }
531
532 /**
533 * Build Membership Block in Contribution Pages.
534 * @todo this was shared on CRM_Contribute_Form_ContributionBase but we are refactoring and simplifying for each
535 * step (main/confirm/thankyou)
536 *
537 * @param int $cid
538 * Contact checked for having a current membership for a particular membership.
539 * @param int|array $selectedMembershipTypeID
540 * Selected membership id.
541 * @param null $isTest
542 *
543 * @return bool
544 * Is this a separate membership payment
545 *
546 * @throws \CiviCRM_API3_Exception
547 * @throws \CRM_Core_Exception
548 */
549 private function buildMembershipBlock($cid, $selectedMembershipTypeID = NULL, $isTest = NULL) {
550 $separateMembershipPayment = FALSE;
551 $this->addOptionalQuickFormElement('auto_renew');
552 if ($this->_membershipBlock) {
553 $this->_currentMemberships = [];
554
555 $membershipTypeIds = $membershipTypes = $radio = $radioOptAttrs = [];
556 $membershipPriceset = (!empty($this->_priceSetId) && $this->_useForMember);
557
558 $allowAutoRenewMembership = $autoRenewOption = FALSE;
559 $autoRenewMembershipTypeOptions = [];
560
561 $separateMembershipPayment = $this->_membershipBlock['is_separate_payment'] ?? NULL;
562
563 if ($membershipPriceset) {
564 foreach ($this->_priceSet['fields'] as $pField) {
565 if (empty($pField['options'])) {
566 continue;
567 }
568 foreach ($pField['options'] as $opId => $opValues) {
569 if (empty($opValues['membership_type_id'])) {
570 continue;
571 }
572 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
573 }
574 }
575 }
576 elseif (!empty($this->_membershipBlock['membership_types'])) {
577 $membershipTypeIds = explode(',', $this->_membershipBlock['membership_types']);
578 }
579
580 if (!empty($membershipTypeIds)) {
581 //set status message if wrong membershipType is included in membershipBlock
582 if (isset($this->_mid) && !$membershipPriceset) {
583 $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
584 $this->_mid,
585 'membership_type_id'
586 );
587 if (!in_array($membershipTypeID, $membershipTypeIds)) {
588 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');
589 }
590 }
591
592 $membershipTypeValues = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, $membershipTypeIds);
593 $this->_membershipTypeValues = $membershipTypeValues;
594 $endDate = NULL;
595
596 // Check if we support auto-renew on this contribution page
597 // FIXME: If any of the payment processors do NOT support recurring you cannot setup an
598 // auto-renew payment even if that processor is not selected.
599 $allowAutoRenewOpt = TRUE;
600 if (is_array($this->_paymentProcessors)) {
601 foreach ($this->_paymentProcessors as $id => $val) {
602 if ($id && !$val['is_recur']) {
603 $allowAutoRenewOpt = FALSE;
604 }
605 }
606 }
607 foreach ($membershipTypeIds as $value) {
608 $memType = $membershipTypeValues[$value];
609 if ($selectedMembershipTypeID != NULL) {
610 if ($memType['id'] == $selectedMembershipTypeID) {
611 $this->assign('minimum_fee', $memType['minimum_fee'] ?? NULL);
612 $this->assign('membership_name', $memType['name']);
613 if ($cid) {
614 $membership = new CRM_Member_DAO_Membership();
615 $membership->contact_id = $cid;
616 $membership->membership_type_id = $memType['id'];
617 if ($membership->find(TRUE)) {
618 $this->assign('renewal_mode', TRUE);
619 $memType['current_membership'] = $membership->end_date;
620 $this->_currentMemberships[$membership->membership_type_id] = $membership->membership_type_id;
621 }
622 }
623 $membershipTypes[] = $memType;
624 }
625 }
626 elseif ($memType['is_active']) {
627
628 if ($allowAutoRenewOpt) {
629 $javascriptMethod = ['onclick' => "return showHideAutoRenew( this.value );"];
630 $isAvailableAutoRenew = $this->_membershipBlock['auto_renew'][$value] ?? 1;
631 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int) $memType['auto_renew'] * $isAvailableAutoRenew;
632 $allowAutoRenewMembership = TRUE;
633 }
634 else {
635 $javascriptMethod = NULL;
636 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = 0;
637 }
638
639 //add membership type.
640 $radio[$memType['id']] = NULL;
641 $radioOptAttrs[$memType['id']] = $javascriptMethod;
642 if ($cid) {
643 $membership = new CRM_Member_DAO_Membership();
644 $membership->contact_id = $cid;
645 $membership->membership_type_id = $memType['id'];
646
647 //show current membership, skip pending and cancelled membership records,
648 //because we take first membership record id for renewal
649 $membership->whereAdd('status_id != 5 AND status_id !=6');
650
651 if (!is_null($isTest)) {
652 $membership->is_test = $isTest;
653 }
654
655 //CRM-4297
656 $membership->orderBy('end_date DESC');
657
658 if ($membership->find(TRUE)) {
659 if (!$membership->end_date) {
660 unset($radio[$memType['id']]);
661 unset($radioOptAttrs[$memType['id']]);
662 $this->assign('islifetime', TRUE);
663 continue;
664 }
665 $this->assign('renewal_mode', TRUE);
666 $this->_currentMemberships[$membership->membership_type_id] = $membership->membership_type_id;
667 $memType['current_membership'] = $membership->end_date;
668 if (!$endDate) {
669 $endDate = $memType['current_membership'];
670 $this->_defaultMemTypeId = $memType['id'];
671 }
672 if ($memType['current_membership'] < $endDate) {
673 $endDate = $memType['current_membership'];
674 $this->_defaultMemTypeId = $memType['id'];
675 }
676 }
677 }
678 $membershipTypes[] = $memType;
679 }
680 }
681 }
682
683 $this->assign('membershipBlock', $this->_membershipBlock);
684 $this->assign('showRadio', TRUE);
685 $this->assign('membershipTypes', $membershipTypes);
686 $this->assign('allowAutoRenewMembership', $allowAutoRenewMembership);
687 $this->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
688 //give preference to user submitted auto_renew value.
689 $takeUserSubmittedAutoRenew = (!empty($_POST) || $this->isSubmitted());
690 $this->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
691
692 // Assign autorenew option (0:hide,1:optional,2:required) so we can use it in confirmation etc.
693 $autoRenewOption = CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($this->_priceSetId);
694 //$selectedMembershipTypeID is retrieved as an array for membership priceset if multiple
695 //options for different organisation is selected on the contribution page.
696 if (is_numeric($selectedMembershipTypeID) && isset($membershipTypeValues[$selectedMembershipTypeID]['auto_renew'])) {
697 $this->assign('autoRenewOption', $membershipTypeValues[$selectedMembershipTypeID]['auto_renew']);
698 }
699 else {
700 $this->assign('autoRenewOption', $autoRenewOption);
701 }
702
703 if (!$membershipPriceset) {
704 if (!$this->_membershipBlock['is_required']) {
705 $this->assign('showRadioNoThanks', TRUE);
706 $radio['no_thanks'] = NULL;
707 $this->addRadio('selectMembership', NULL, $radio, [], NULL, FALSE, $radioOptAttrs);
708 }
709 elseif ($this->_membershipBlock['is_required'] && count($radio) == 1) {
710 $temp = array_keys($radio);
711 $this->add('hidden', 'selectMembership', $temp[0], ['id' => 'selectMembership']);
712 $this->assign('singleMembership', TRUE);
713 $this->assign('showRadio', FALSE);
714 }
715 else {
716 foreach ($radioOptAttrs as $opt => $attrs) {
717 $attrs['class'] = ' required';
718 }
719 $this->addRadio('selectMembership', NULL, $radio, [], NULL, FALSE, $radioOptAttrs);
720 }
721
722 $this->addRule('selectMembership', ts('Please select one of the memberships.'), 'required');
723 }
724
725 if ((!$this->_values['is_pay_later'] || is_array($this->_paymentProcessors)) && ($allowAutoRenewMembership || $autoRenewOption)) {
726 if ($autoRenewOption == 2) {
727 $this->addElement('hidden', 'auto_renew', ts('Please renew my membership automatically.'));
728 }
729 else {
730 $this->addElement('checkbox', 'auto_renew', ts('Please renew my membership automatically.'));
731 }
732 }
733
734 }
735
736 return $separateMembershipPayment;
737 }
738
739 /**
740 * Build elements to collect information for recurring contributions.
741 *
742 *
743 * @param CRM_Core_Form $form
744 */
745 public static function buildRecur(&$form) {
746 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur');
747 $className = get_class($form);
748
749 $form->assign('is_recur_interval', CRM_Utils_Array::value('is_recur_interval', $form->_values));
750 $form->assign('is_recur_installments', CRM_Utils_Array::value('is_recur_installments', $form->_values));
751 $paymentObject = $form->getVar('_paymentObject');
752 if ($paymentObject) {
753 $form->assign('recurringHelpText', $paymentObject->getText('contributionPageRecurringHelp', [
754 'is_recur_installments' => !empty($form->_values['is_recur_installments']),
755 'is_email_receipt' => !empty($form->_values['is_email_receipt']),
756 ]));
757 }
758
759 $frUnits = $form->_values['recur_frequency_unit'] ?? NULL;
760 $frequencyUnits = CRM_Core_OptionGroup::values('recur_frequency_units', FALSE, FALSE, TRUE);
761 if (empty($frUnits) &&
762 $className == 'CRM_Contribute_Form_Contribution'
763 ) {
764 $frUnits = implode(CRM_Core_DAO::VALUE_SEPARATOR,
765 CRM_Core_OptionGroup::values('recur_frequency_units', FALSE, FALSE, FALSE, NULL, 'value')
766 );
767 }
768
769 $unitVals = explode(CRM_Core_DAO::VALUE_SEPARATOR, $frUnits);
770
771 // FIXME: Ideally we should freeze select box if there is only
772 // one option but looks there is some problem /w QF freeze.
773 //if ( count( $units ) == 1 ) {
774 //$frequencyUnit->freeze( );
775 //}
776
777 $form->add('text', 'installments', ts('installments'),
778 $attributes['installments']
779 );
780 $form->addRule('installments', ts('Number of installments must be a whole number.'), 'integer');
781
782 $is_recur_label = ts('I want to contribute this amount every');
783
784 // CRM 10860, display text instead of a dropdown if there's only 1 frequency unit
785 if (count($unitVals) == 1) {
786 $form->assign('one_frequency_unit', TRUE);
787 $form->add('hidden', 'frequency_unit', $unitVals[0]);
788 if (!empty($form->_values['is_recur_interval']) || $className == 'CRM_Contribute_Form_Contribution') {
789 $unit = CRM_Contribute_BAO_Contribution::getUnitLabelWithPlural($unitVals[0]);
790 $form->assign('frequency_unit', $unit);
791 }
792 else {
793 $is_recur_label = ts('I want to contribute this amount every %1',
794 [1 => $frequencyUnits[$unitVals[0]]]
795 );
796 $form->assign('all_text_recur', TRUE);
797 }
798 }
799 else {
800 $form->assign('one_frequency_unit', FALSE);
801 $units = [];
802 foreach ($unitVals as $key => $val) {
803 if (array_key_exists($val, $frequencyUnits)) {
804 $units[$val] = $frequencyUnits[$val];
805 if (!empty($form->_values['is_recur_interval']) || $className == 'CRM_Contribute_Form_Contribution') {
806 $units[$val] = CRM_Contribute_BAO_Contribution::getUnitLabelWithPlural($val);
807 $unit = ts('Every');
808 }
809 }
810 }
811 $frequencyUnit = &$form->addElement('select', 'frequency_unit', NULL, $units, ['aria-label' => ts('Frequency Unit')]);
812 }
813
814 if (!empty($form->_values['is_recur_interval']) || $className == 'CRM_Contribute_Form_Contribution') {
815 $form->add('text', 'frequency_interval', $unit, $attributes['frequency_interval'] + ['aria-label' => ts('Every')]);
816 $form->addRule('frequency_interval', ts('Frequency must be a whole number (EXAMPLE: Every 3 months).'), 'integer');
817 }
818 else {
819 // make sure frequency_interval is submitted as 1 if given no choice to user.
820 $form->add('hidden', 'frequency_interval', 1);
821 }
822
823 $form->add('checkbox', 'is_recur', $is_recur_label, NULL);
824 }
825
826 /**
827 * Global form rule.
828 *
829 * @param array $fields
830 * The input form values.
831 * @param array $files
832 * The uploaded files if any.
833 * @param \CRM_Contribute_Form_Contribution_Main $self
834 *
835 * @return bool|array
836 * true if no errors, else array of errors
837 */
838 public static function formRule($fields, $files, $self) {
839 $errors = [];
840 $amount = self::computeAmount($fields, $self->_values);
841 if (!empty($fields['auto_renew']) && empty($fields['payment_processor_id'])) {
842 $errors['auto_renew'] = ts('You cannot have auto-renewal on if you are paying later.');
843 }
844
845 if ((!empty($fields['selectMembership']) &&
846 $fields['selectMembership'] != 'no_thanks'
847 ) ||
848 (!empty($fields['priceSetId']) &&
849 $self->_useForMember
850 )
851 ) {
852 $isTest = $self->_action & CRM_Core_Action::PREVIEW;
853 $lifeMember = CRM_Member_BAO_Membership::getAllContactMembership($self->_membershipContactID, $isTest, TRUE);
854
855 $membershipOrgDetails = CRM_Member_BAO_MembershipType::getAllMembershipTypes();
856 $unallowedOrgs = [];
857 foreach (array_keys($lifeMember) as $memTypeId) {
858 $unallowedOrgs[] = $membershipOrgDetails[$memTypeId]['member_of_contact_id'];
859 }
860 }
861
862 //check for atleast one pricefields should be selected
863 if (!empty($fields['priceSetId']) && empty($self->_ccid)) {
864 $priceField = new CRM_Price_DAO_PriceField();
865 $priceField->price_set_id = $fields['priceSetId'];
866 $priceField->orderBy('weight');
867 $priceField->find();
868
869 $check = [];
870 $membershipIsActive = TRUE;
871 $previousId = $otherAmount = FALSE;
872 while ($priceField->fetch()) {
873
874 if ($self->isQuickConfig() && ($priceField->name == 'contribution_amount' || $priceField->name == 'membership_amount')) {
875 $previousId = $priceField->id;
876 if ($priceField->name == 'membership_amount' && !$priceField->is_active) {
877 $membershipIsActive = FALSE;
878 }
879 }
880 if ($priceField->name == 'other_amount') {
881 if ($self->_quickConfig && empty($fields["price_{$priceField->id}"]) &&
882 array_key_exists("price_{$previousId}", $fields) && isset($fields["price_{$previousId}"]) && $self->_values['fee'][$previousId]['name'] == 'contribution_amount' && empty($fields["price_{$previousId}"])
883 ) {
884 $otherAmount = $priceField->id;
885 }
886 elseif (!empty($fields["price_{$priceField->id}"])) {
887 $otherAmountVal = CRM_Utils_Rule::cleanMoney($fields["price_{$priceField->id}"]);
888 $min = $self->_values['min_amount'] ?? NULL;
889 $max = $self->_values['max_amount'] ?? NULL;
890 if ($min && $otherAmountVal < $min) {
891 $errors["price_{$priceField->id}"] = ts('Contribution amount must be at least %1',
892 [1 => $min]
893 );
894 }
895 if ($max && $otherAmountVal > $max) {
896 $errors["price_{$priceField->id}"] = ts('Contribution amount cannot be more than %1.',
897 [1 => $max]
898 );
899 }
900 }
901 }
902 if (!empty($fields["price_{$priceField->id}"]) || ($previousId == $priceField->id && isset($fields["price_{$previousId}"])
903 && empty($fields["price_{$previousId}"]))
904 ) {
905 $check[] = $priceField->id;
906 }
907 }
908
909 $currentMemberships = NULL;
910 if ($membershipIsActive) {
911 $is_test = $self->_mode != 'live' ? 1 : 0;
912 $memContactID = $self->_membershipContactID;
913
914 // For anonymous user check using dedupe rule
915 // if user has Cancelled Membership
916 if (!$memContactID) {
917 $memContactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($fields, 'Individual', 'Unsupervised', [], FALSE);
918 }
919 $currentMemberships = CRM_Member_BAO_Membership::getContactsCancelledMembership($memContactID,
920 $is_test
921 );
922
923 foreach ($self->_values['fee'] as $fieldKey => $fieldValue) {
924 if ($fieldValue['html_type'] != 'Text' && !empty($fields['price_' . $fieldKey])) {
925 if (!is_array($fields['price_' . $fieldKey]) && isset($fieldValue['options'][$fields['price_' . $fieldKey]])) {
926 if (array_key_exists('membership_type_id', $fieldValue['options'][$fields['price_' . $fieldKey]])
927 && in_array($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'], $currentMemberships)
928 ) {
929 $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'])]);
930 }
931 }
932 else {
933 if (is_array($fields['price_' . $fieldKey])) {
934 foreach (array_keys($fields['price_' . $fieldKey]) as $key) {
935 if (array_key_exists('membership_type_id', $fieldValue['options'][$key])
936 && in_array($fieldValue['options'][$key]['membership_type_id'], $currentMemberships)
937 ) {
938 $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'])]);
939 }
940 }
941 }
942 }
943 }
944 }
945 }
946
947 // CRM-12233
948 if ($membershipIsActive && empty($self->_membershipBlock['is_required'])
949 && $self->isFormSupportsNonMembershipContributions()
950 ) {
951 $membershipFieldId = $contributionFieldId = $errorKey = $otherFieldId = NULL;
952 foreach ($self->_values['fee'] as $fieldKey => $fieldValue) {
953 // if 'No thank you' membership is selected then set $membershipFieldId
954 if ($fieldValue['name'] == 'membership_amount' && CRM_Utils_Array::value('price_' . $fieldKey, $fields) == 0) {
955 $membershipFieldId = $fieldKey;
956 }
957 elseif ($membershipFieldId) {
958 if ($fieldValue['name'] == 'other_amount') {
959 $otherFieldId = $fieldKey;
960 }
961 elseif ($fieldValue['name'] == 'contribution_amount') {
962 $contributionFieldId = $fieldKey;
963 }
964
965 if (!$errorKey || CRM_Utils_Array::value('price_' . $contributionFieldId, $fields) == '0') {
966 $errorKey = $fieldKey;
967 }
968 }
969 }
970 // $membershipFieldId is set and additional amount is 'No thank you' or NULL then throw error
971 if ($membershipFieldId && !(CRM_Utils_Array::value('price_' . $contributionFieldId, $fields, -1) > 0) && empty($fields['price_' . $otherFieldId])) {
972 $errors["price_{$errorKey}"] = ts('Additional Contribution is required.');
973 }
974 }
975 if (empty($check) && empty($self->_ccid)) {
976 if ($self->_useForMember == 1 && $membershipIsActive) {
977 $errors['_qf_default'] = ts('Select at least one option from Membership Type(s).');
978 }
979 else {
980 $errors['_qf_default'] = ts('Select at least one option from Contribution(s).');
981 }
982 }
983 if ($otherAmount && !empty($check)) {
984 $errors["price_{$otherAmount}"] = ts('Amount is required field.');
985 }
986
987 if ($self->_useForMember == 1 && !empty($check) && $membershipIsActive) {
988 $priceFieldIDS = [];
989 $priceFieldMemTypes = [];
990
991 foreach ($self->_priceSet['fields'] as $priceId => $value) {
992 if (!empty($fields['price_' . $priceId]) || ($self->_quickConfig && $value['name'] == 'membership_amount' && empty($self->_membershipBlock['is_required']))) {
993 if (!empty($fields['price_' . $priceId]) && is_array($fields['price_' . $priceId])) {
994 foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) {
995 if ($isSet) {
996 $priceFieldIDS[] = $priceFldVal;
997 }
998 }
999 }
1000 elseif (!$value['is_enter_qty'] && !empty($fields['price_' . $priceId])) {
1001 // The check for {!$value['is_enter_qty']} is done since, quantity fields allow entering
1002 // quantity. And the quantity can't be conisdered as civicrm_price_field_value.id, CRM-9577
1003 $priceFieldIDS[] = $fields['price_' . $priceId];
1004 }
1005
1006 if (!empty($value['options'])) {
1007 foreach ($value['options'] as $val) {
1008 if (!empty($val['membership_type_id']) && (
1009 ($fields['price_' . $priceId] == $val['id']) ||
1010 (isset($fields['price_' . $priceId]) && !empty($fields['price_' . $priceId][$val['id']]))
1011 )
1012 ) {
1013 $priceFieldMemTypes[] = $val['membership_type_id'];
1014 }
1015 }
1016 }
1017 }
1018 }
1019
1020 if (!empty($lifeMember)) {
1021 foreach ($priceFieldIDS as $priceFieldId) {
1022 if (($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) &&
1023 in_array($membershipOrgDetails[$id]['member_of_contact_id'], $unallowedOrgs)
1024 ) {
1025 $errors['_qf_default'] = ts('You already have a lifetime membership and cannot select a membership with a shorter term.');
1026 break;
1027 }
1028 }
1029 }
1030
1031 if (!empty($priceFieldIDS)) {
1032 $ids = implode(',', $priceFieldIDS);
1033
1034 $priceFieldIDS['id'] = $fields['priceSetId'];
1035 $self->set('memberPriceFieldIDS', $priceFieldIDS);
1036 $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids);
1037 foreach ($count as $id => $occurrence) {
1038 if ($occurrence > 1) {
1039 $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.');
1040 break;
1041 }
1042 }
1043 }
1044
1045 if (empty($priceFieldMemTypes) && $self->_membershipBlock['is_required'] == 1) {
1046 $errors['_qf_default'] = ts('Please select at least one membership option.');
1047 }
1048 }
1049
1050 CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'],
1051 $fields, $lineItem
1052 );
1053
1054 $minAmt = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $fields['priceSetId'], 'min_amount');
1055 if ($fields['amount'] < 0) {
1056 $errors['_qf_default'] = ts('Contribution can not be less than zero. Please select the options accordingly');
1057 }
1058 elseif (!empty($minAmt) && $fields['amount'] < $minAmt) {
1059 $errors['_qf_default'] = ts('A minimum amount of %1 should be selected from Contribution(s).', [
1060 1 => CRM_Utils_Money::format($minAmt),
1061 ]);
1062 }
1063
1064 $amount = $fields['amount'];
1065 }
1066
1067 if (isset($fields['selectProduct']) &&
1068 $fields['selectProduct'] != 'no_thanks'
1069 ) {
1070 $productDAO = new CRM_Contribute_DAO_Product();
1071 $productDAO->id = $fields['selectProduct'];
1072 $productDAO->find(TRUE);
1073 $min_amount = $productDAO->min_contribution;
1074
1075 if ($amount < $min_amount) {
1076 $errors['selectProduct'] = ts('The premium you have selected requires a minimum contribution of %1', [1 => CRM_Utils_Money::format($min_amount)]);
1077 CRM_Core_Session::setStatus($errors['selectProduct']);
1078 }
1079 }
1080
1081 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
1082 CRM_Contribute_BAO_ContributionRecur::validateRecurContribution($fields, $files, $self, $errors);
1083
1084 if (!empty($fields['is_recur']) && empty($fields['payment_processor_id'])) {
1085 $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.');
1086 }
1087
1088 // validate PCP fields - if not anonymous, we need a nick name value
1089 if ($self->_pcpId && !empty($fields['pcp_display_in_roll']) &&
1090 empty($fields['pcp_is_anonymous']) &&
1091 CRM_Utils_Array::value('pcp_roll_nickname', $fields) == ''
1092 ) {
1093 $errors['pcp_roll_nickname'] = ts('Please enter a name to include in the Honor Roll, or select \'contribute anonymously\'.');
1094 }
1095
1096 // return if this is express mode
1097 $config = CRM_Core_Config::singleton();
1098 if ($self->_paymentProcessor &&
1099 (int) $self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON
1100 ) {
1101 if (!empty($fields[$self->_expressButtonName . '_x']) || !empty($fields[$self->_expressButtonName . '_y']) ||
1102 !empty($fields[$self->_expressButtonName])
1103 ) {
1104 return $errors;
1105 }
1106 }
1107
1108 //validate the pledge fields.
1109 if (!empty($self->_values['pledge_block_id'])) {
1110 //validation for pledge payment.
1111 if (!empty($self->_values['pledge_id'])) {
1112 if (empty($fields['pledge_amount'])) {
1113 $errors['pledge_amount'] = ts('At least one payment option needs to be checked.');
1114 }
1115 }
1116 elseif (!empty($fields['is_pledge'])) {
1117 if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_installments', $fields)) == FALSE) {
1118 $errors['pledge_installments'] = ts('Please enter a valid number of pledge installments.');
1119 }
1120 else {
1121 if (!isset($fields['pledge_installments'])) {
1122 $errors['pledge_installments'] = ts('Pledge Installments is required field.');
1123 }
1124 elseif (CRM_Utils_Array::value('pledge_installments', $fields) == 1) {
1125 $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.');
1126 }
1127 elseif (empty($fields['pledge_installments'])) {
1128 $errors['pledge_installments'] = ts('Pledge Installments field must be > 1.');
1129 }
1130 }
1131
1132 //validation for Pledge Frequency Interval.
1133 if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_frequency_interval', $fields)) == FALSE) {
1134 $errors['pledge_frequency_interval'] = ts('Please enter a valid Pledge Frequency Interval.');
1135 }
1136 else {
1137 if (!isset($fields['pledge_frequency_interval'])) {
1138 $errors['pledge_frequency_interval'] = ts('Pledge Frequency Interval. is required field.');
1139 }
1140 elseif (empty($fields['pledge_frequency_interval'])) {
1141 $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0');
1142 }
1143 }
1144 }
1145 }
1146
1147 // if the user has chosen a free membership or the amount is less than zero
1148 // i.e. we don't need to validate payment related fields or profiles.
1149 if ((float) $amount <= 0.0) {
1150 return $errors;
1151 }
1152
1153 if (!isset($fields['payment_processor_id'])) {
1154 $errors['payment_processor_id'] = ts('Payment Method is a required field.');
1155 }
1156 else {
1157 CRM_Core_Payment_Form::validatePaymentInstrument(
1158 $fields['payment_processor_id'],
1159 $fields,
1160 $errors,
1161 (!$self->_isBillingAddressRequiredForPayLater ? NULL : 'billing')
1162 );
1163 }
1164
1165 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
1166 if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
1167 $customizedValue = CRM_Core_PseudoConstant::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
1168 if ($customizedValue == $greetingType && empty($fielse[$greeting . '_custom'])) {
1169 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
1170 [1 => ucwords(str_replace('_', " ", $greeting))]
1171 );
1172 }
1173 }
1174 }
1175
1176 return empty($errors) ? TRUE : $errors;
1177 }
1178
1179 /**
1180 * Compute amount to be paid.
1181 *
1182 * @param array $params
1183 * @param array $formValues
1184 *
1185 * @return int|mixed|null|string
1186 */
1187 public static function computeAmount($params, $formValues) {
1188 $amount = 0;
1189 // First clean up the other amount field if present.
1190 if (isset($params['amount_other'])) {
1191 $params['amount_other'] = CRM_Utils_Rule::cleanMoney($params['amount_other']);
1192 }
1193
1194 if (CRM_Utils_Array::value('amount', $params) == 'amount_other_radio' || !empty($params['amount_other'])) {
1195 $amount = $params['amount_other'];
1196 }
1197 elseif (!empty($params['pledge_amount'])) {
1198 foreach ($params['pledge_amount'] as $paymentId => $dontCare) {
1199 $amount += CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount');
1200 }
1201 }
1202 else {
1203 if (!empty($formValues['amount'])) {
1204 $amountID = $params['amount'] ?? NULL;
1205
1206 if ($amountID) {
1207 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1208 // function to get correct amount level consistently. Remove setting of the amount level in
1209 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1210 // to cover all variants.
1211 $params['amount_level'] = $formValues[$amountID]['label'] ?? NULL;
1212 $amount = $formValues[$amountID]['value'] ?? NULL;
1213 }
1214 }
1215 }
1216 return $amount;
1217 }
1218
1219 /**
1220 * Process the form submission.
1221 */
1222 public function postProcess() {
1223 // we first reset the confirm page so it accepts new values
1224 $this->controller->resetPage('Confirm');
1225
1226 // get the submitted form values.
1227 $params = $this->controller->exportValues($this->_name);
1228 $this->submit($params);
1229
1230 if (empty($this->_values['is_confirm_enabled'])) {
1231 $this->skipToThankYouPage();
1232 }
1233
1234 }
1235
1236 /**
1237 * Submit function.
1238 *
1239 * This is the guts of the postProcess made also accessible to the test suite.
1240 *
1241 * @param array $params
1242 * Submitted values.
1243 *
1244 * @throws \CiviCRM_API3_Exception
1245 */
1246 public function submit($params) {
1247 //carry campaign from profile.
1248 if (array_key_exists('contribution_campaign_id', $params)) {
1249 $params['campaign_id'] = $params['contribution_campaign_id'];
1250 }
1251
1252 $params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
1253
1254 // @todo refactor this & leverage it from the unit tests.
1255 if (!empty($params['priceSetId'])) {
1256 $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
1257 if ($is_quick_config) {
1258 $priceField = new CRM_Price_DAO_PriceField();
1259 $priceField->price_set_id = $params['priceSetId'];
1260 $priceField->orderBy('weight');
1261 $priceField->find();
1262
1263 $priceOptions = [];
1264 while ($priceField->fetch()) {
1265 CRM_Price_BAO_PriceFieldValue::getValues($priceField->id, $priceOptions);
1266 if (($selectedPriceOptionID = CRM_Utils_Array::value("price_{$priceField->id}", $params)) != FALSE && $selectedPriceOptionID > 0) {
1267 switch ($priceField->name) {
1268 case 'membership_amount':
1269 $this->_params['selectMembership'] = $params['selectMembership'] = $priceOptions[$selectedPriceOptionID]['membership_type_id'] ?? NULL;
1270 $this->set('selectMembership', $params['selectMembership']);
1271
1272 case 'contribution_amount':
1273 $params['amount'] = $selectedPriceOptionID;
1274 if ($priceField->name == 'contribution_amount' ||
1275 ($priceField->name == 'membership_amount' &&
1276 CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock) == 0)
1277 ) {
1278 $this->_values['amount'] = $priceOptions[$selectedPriceOptionID]['amount'] ?? NULL;
1279 }
1280 $this->_values[$selectedPriceOptionID]['value'] = $priceOptions[$selectedPriceOptionID]['amount'] ?? NULL;
1281 $this->_values[$selectedPriceOptionID]['label'] = $priceOptions[$selectedPriceOptionID]['label'] ?? NULL;
1282 $this->_values[$selectedPriceOptionID]['amount_id'] = $priceOptions[$selectedPriceOptionID]['id'] ?? NULL;
1283 $this->_values[$selectedPriceOptionID]['weight'] = $priceOptions[$selectedPriceOptionID]['weight'] ?? NULL;
1284 break;
1285
1286 case 'other_amount':
1287 $params['amount_other'] = $selectedPriceOptionID;
1288 break;
1289 }
1290 }
1291 }
1292 }
1293 }
1294
1295 if (!empty($this->_ccid) && !empty($this->_pendingAmount)) {
1296 $params['amount'] = $this->_pendingAmount;
1297 }
1298 else {
1299 // from here on down, $params['amount'] holds a monetary value (or null) rather than an option ID
1300 $params['amount'] = self::computeAmount($params, $this->_values);
1301 }
1302
1303 $params['separate_amount'] = $params['amount'];
1304 // @todo - stepping through the code indicates that amount is always set before this point so it never matters.
1305 // Move more of the above into this function...
1306 $params['amount'] = $this->getMainContributionAmount($params);
1307 //If the membership & contribution is used in contribution page & not separate payment
1308 $memPresent = $membershipLabel = $fieldOption = $is_quick_config = NULL;
1309 $proceFieldAmount = 0;
1310 if (property_exists($this, '_separateMembershipPayment') && $this->_separateMembershipPayment == 0) {
1311 $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
1312 if ($is_quick_config) {
1313 foreach ($this->_priceSet['fields'] as $fieldKey => $fieldVal) {
1314 if ($fieldVal['name'] == 'membership_amount' && !empty($params['price_' . $fieldKey])) {
1315 $fieldId = $fieldVal['id'];
1316 $fieldOption = $params['price_' . $fieldId];
1317 $proceFieldAmount += $fieldVal['options'][$this->_submitValues['price_' . $fieldId]]['amount'];
1318 $memPresent = TRUE;
1319 }
1320 else {
1321 if (!empty($params['price_' . $fieldKey]) && $memPresent && ($fieldVal['name'] == 'other_amount' || $fieldVal['name'] == 'contribution_amount')) {
1322 $fieldId = $fieldVal['id'];
1323 if ($fieldVal['name'] == 'other_amount') {
1324 $proceFieldAmount += $this->_submitValues['price_' . $fieldId];
1325 }
1326 elseif ($fieldVal['name'] == 'contribution_amount' && $this->_submitValues['price_' . $fieldId] > 0) {
1327 $proceFieldAmount += $fieldVal['options'][$this->_submitValues['price_' . $fieldId]]['amount'];
1328 }
1329 unset($params['price_' . $fieldId]);
1330 break;
1331 }
1332 }
1333 }
1334 }
1335 }
1336
1337 if (!isset($params['amount_other'])) {
1338 $this->set('amount_level', CRM_Utils_Array::value('amount_level', $params));
1339 }
1340
1341 if (!empty($this->_ccid)) {
1342 $this->set('lineItem', $this->_lineItem);
1343 }
1344 elseif ($priceSetId = CRM_Utils_Array::value('priceSetId', $params)) {
1345 $lineItem = [];
1346 $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1347 if ($is_quick_config) {
1348 foreach ($this->_values['fee'] as $key => & $val) {
1349 if ($val['name'] == 'other_amount' && $val['html_type'] == 'Text' && !empty($params['price_' . $key])) {
1350 // Clean out any currency symbols.
1351 $params['price_' . $key] = CRM_Utils_Rule::cleanMoney($params['price_' . $key]);
1352 if ($params['price_' . $key] != 0) {
1353 foreach ($val['options'] as $optionKey => & $options) {
1354 $options['amount'] = $params['price_' . $key] ?? NULL;
1355 break;
1356 }
1357 }
1358 $params['price_' . $key] = 1;
1359 break;
1360 }
1361 }
1362 }
1363
1364 if ($this->_membershipBlock) {
1365 $this->processAmountAndGetAutoRenew($this->_values['fee'], $params, $lineItem[$priceSetId], $priceSetId);
1366 }
1367 else {
1368 CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem[$priceSetId], $priceSetId);
1369 }
1370
1371 if ($params['tax_amount']) {
1372 $this->set('tax_amount', $params['tax_amount']);
1373 }
1374
1375 if ($proceFieldAmount) {
1376 $lineItem[$params['priceSetId']][$fieldOption]['unit_price'] = $proceFieldAmount;
1377 $lineItem[$params['priceSetId']][$fieldOption]['line_total'] = $proceFieldAmount;
1378 if (isset($lineItem[$params['priceSetId']][$fieldOption]['tax_amount'])) {
1379 $proceFieldAmount += $lineItem[$params['priceSetId']][$fieldOption]['tax_amount'];
1380 }
1381 if (!$this->_membershipBlock['is_separate_payment']) {
1382 //require when separate membership not used
1383 $params['amount'] = $proceFieldAmount;
1384 }
1385 }
1386 $this->set('lineItem', $lineItem);
1387 }
1388
1389 if ($params['amount'] != 0 && (($this->_values['is_pay_later'] &&
1390 empty($this->_paymentProcessor) &&
1391 !array_key_exists('hidden_processor', $params)) ||
1392 empty($params['payment_processor_id']))
1393 ) {
1394 $params['is_pay_later'] = 1;
1395 }
1396 else {
1397 $params['is_pay_later'] = 0;
1398 }
1399
1400 // Would be nice to someday understand the point of this set.
1401 $this->set('is_pay_later', $params['is_pay_later']);
1402 // assign pay later stuff
1403 $this->_params['is_pay_later'] = $params['is_pay_later'];
1404 $this->assign('is_pay_later', $params['is_pay_later']);
1405 $this->assign('pay_later_text', $params['is_pay_later'] ? $this->_values['pay_later_text'] : NULL);
1406 $this->assign('pay_later_receipt', ($params['is_pay_later'] && isset($this->_values['pay_later_receipt'])) ? $this->_values['pay_later_receipt'] : NULL);
1407
1408 if ($this->_membershipBlock && $this->_membershipBlock['is_separate_payment'] && !empty($params['separate_amount'])) {
1409 $this->set('amount', $params['separate_amount']);
1410 }
1411 else {
1412 $this->set('amount', $params['amount']);
1413 }
1414
1415 // generate and set an invoiceID for this transaction
1416 $invoiceID = md5(uniqid(rand(), TRUE));
1417 $this->set('invoiceID', $invoiceID);
1418 $params['invoiceID'] = $invoiceID;
1419 $title = !empty($this->_values['frontend_title']) ? $this->_values['frontend_title'] : $this->_values['title'];
1420 $params['description'] = ts('Online Contribution') . ': ' . ((!empty($this->_pcpInfo['title']) ? $this->_pcpInfo['title'] : $title));
1421 $params['button'] = $this->controller->getButtonName();
1422 // required only if is_monetary and valid positive amount
1423 if ($this->_values['is_monetary'] &&
1424 !empty($this->_paymentProcessor) &&
1425 ((float) $params['amount'] > 0.0 || $this->hasSeparateMembershipPaymentAmount($params))
1426 ) {
1427 // The concept of contributeMode is deprecated - as should be the 'is_monetary' setting.
1428 $this->setContributeMode();
1429 // Really this setting of $this->_params & params within it should be done earlier on in the function
1430 // probably the values determined here should be reused in confirm postProcess as there is no opportunity to alter anything
1431 // on the confirm page. However as we are dealing with a stable release we go as close to where it is used
1432 // as possible.
1433 // In general the form has a lack of clarity of the logic of why things are set on the form in some cases &
1434 // the logic around when $this->_params is used compared to other params arrays.
1435 $this->_params = array_merge($params, $this->_params);
1436 $this->setRecurringMembershipParams();
1437 if ($this->_paymentProcessor &&
1438 $this->_paymentProcessor['object']->supports('preApproval')
1439 ) {
1440 $this->handlePreApproval($this->_params);
1441 }
1442 }
1443 }
1444
1445 /**
1446 * Assign the billing mode to the template.
1447 *
1448 * This is required for legacy support for contributeMode in templates.
1449 *
1450 * The goal is to remove this parameter & use more relevant parameters.
1451 */
1452 protected function setContributeMode() {
1453 switch ($this->_paymentProcessor['billing_mode']) {
1454 case CRM_Core_Payment::BILLING_MODE_FORM:
1455 $this->set('contributeMode', 'direct');
1456 break;
1457
1458 case CRM_Core_Payment::BILLING_MODE_BUTTON:
1459 $this->set('contributeMode', 'express');
1460 break;
1461
1462 case CRM_Core_Payment::BILLING_MODE_NOTIFY:
1463 $this->set('contributeMode', 'notify');
1464 break;
1465 }
1466
1467 }
1468
1469 /**
1470 * Process confirm function and pass browser to the thank you page.
1471 */
1472 protected function skipToThankYouPage() {
1473 // call the post process hook for the main page before we switch to confirm
1474 $this->postProcessHook();
1475
1476 // build the confirm page
1477 $confirmForm = &$this->controller->_pages['Confirm'];
1478 $confirmForm->preProcess();
1479 $confirmForm->buildQuickForm();
1480
1481 // the confirmation page is valid
1482 $data = &$this->controller->container();
1483 $data['valid']['Confirm'] = 1;
1484
1485 // confirm the contribution
1486 // mainProcess calls the hook also
1487 $confirmForm->mainProcess();
1488 $qfKey = $this->controller->_key;
1489
1490 // redirect to thank you page
1491 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_ThankYou_display=1&qfKey=$qfKey", TRUE, NULL, FALSE));
1492 }
1493
1494 /**
1495 * Set form variables if contribution ID is found
1496 */
1497 public function assignFormVariablesByContributionID() {
1498 if (empty($this->_ccid)) {
1499 return;
1500 }
1501 if (!$this->getContactID()) {
1502 CRM_Core_Error::statusBounce(ts("Returning since there is no contact attached to this contribution id."));
1503 }
1504
1505 $paymentBalance = CRM_Contribute_BAO_Contribution::getContributionBalance($this->_ccid);
1506 //bounce if the contribution is not pending.
1507 if ((float) $paymentBalance <= 0) {
1508 CRM_Core_Error::statusBounce(ts("Returning since contribution has already been handled."));
1509 }
1510 if (!empty($paymentBalance)) {
1511 $this->_pendingAmount = $paymentBalance;
1512 $this->assign('pendingAmount', $this->_pendingAmount);
1513 }
1514
1515 if ($taxAmount = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_ccid, 'tax_amount')) {
1516 $this->set('tax_amount', $taxAmount);
1517 $this->assign('taxAmount', $taxAmount);
1518 }
1519
1520 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($this->_ccid);
1521 foreach (array_keys($lineItems) as $id) {
1522 $lineItems[$id]['id'] = $id;
1523 }
1524 $itemId = key($lineItems);
1525 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1526 $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1527 }
1528
1529 if (!empty($lineItems[$itemId]['price_field_id'])) {
1530 $this->_lineItem[$this->_priceSetId] = $lineItems;
1531 }
1532 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
1533 $this->assign('lineItem', $this->_lineItem);
1534 $this->assign('is_quick_config', $isQuickConfig);
1535 $this->assign('priceSetID', $this->_priceSetId);
1536 }
1537
1538 /**
1539 * Function for unit tests on the postProcess function.
1540 *
1541 * @param array $params
1542 *
1543 * @throws \CiviCRM_API3_Exception
1544 */
1545 public function testSubmit($params) {
1546 $_SERVER['REQUEST_METHOD'] = 'GET';
1547 $this->controller = new CRM_Contribute_Controller_Contribution();
1548 $this->submit($params);
1549 }
1550
1551 /**
1552 * Has a separate membership payment amount been configured.
1553 *
1554 * @param array $params
1555 *
1556 * @return mixed
1557 * @throws \CiviCRM_API3_Exception
1558 */
1559 protected function hasSeparateMembershipPaymentAmount($params) {
1560 return $this->_separateMembershipPayment && (int) CRM_Member_BAO_MembershipType::getMembershipType($params['selectMembership'])['minimum_fee'];
1561 }
1562
1563 }