revert commit that modified getRecurDetails()
[civicrm-core.git] / CRM / Contribute / Form / ContributionBase.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
18/**
f92d1e2a 19 * This class generates form components for processing a contribution.
6a488035
TO
20 */
21class CRM_Contribute_Form_ContributionBase extends CRM_Core_Form {
573aa07e 22 use CRM_Financial_Form_FrontEndPaymentFormTrait;
6a488035
TO
23
24 /**
f92d1e2a 25 * The id of the contribution page that we are processing.
6a488035
TO
26 *
27 * @var int
6a488035
TO
28 */
29 public $_id;
30
31 /**
100fef9d 32 * The mode that we are in
6a488035
TO
33 *
34 * @var string
35 * @protect
36 */
37 public $_mode;
38
39 /**
100fef9d 40 * The contact id related to a membership
6a488035
TO
41 *
42 * @var int
6a488035
TO
43 */
44 public $_membershipContactID;
45
46 /**
100fef9d 47 * The values for the contribution db object
6a488035
TO
48 *
49 * @var array
6a488035
TO
50 */
51 public $_values;
52
53 /**
100fef9d 54 * The paymentProcessor attributes for this page
6a488035
TO
55 *
56 * @var array
6a488035
TO
57 */
58 public $_paymentProcessor;
1b9f9ca3 59
6a488035
TO
60 public $_paymentObject = NULL;
61
62 /**
63 * The membership block for this page
64 *
65 * @var array
6a488035
TO
66 */
67 public $_membershipBlock = NULL;
68
f64a217a
EM
69 /**
70 * Does this form support a separate membership payment
71 * @var bool
72 */
73 protected $_separateMembershipPayment;
6a488035
TO
74
75 /**
76 * The params submitted by the form and computed by the app
77 *
78 * @var array
6a488035 79 */
be2fb01f 80 public $_params = [];
6a488035
TO
81
82 /**
83 * The fields involved in this contribution page
84 *
85 * @var array
6a488035 86 */
be2fb01f 87 public $_fields = [];
6a488035
TO
88
89 /**
f92d1e2a 90 * The billing location id for this contribution page.
6a488035
TO
91 *
92 * @var int
6a488035
TO
93 */
94 public $_bltID;
95
96 /**
97 * Cache the amount to make things easier
98 *
99 * @var float
6a488035
TO
100 */
101 public $_amount;
102
103 /**
100fef9d 104 * Pcp id
6a488035 105 *
9f266042 106 * @var int
6a488035
TO
107 */
108 public $_pcpId;
109
110 /**
100fef9d 111 * Pcp block
6a488035
TO
112 *
113 * @var array
6a488035
TO
114 */
115 public $_pcpBlock;
116
117 /**
100fef9d 118 * Pcp info
6a488035
TO
119 *
120 * @var array
6a488035
TO
121 */
122 public $_pcpInfo;
123
5b757295 124 /**
125 * The contact id of the person for whom membership is being added or renewed based on the cid in the url,
126 * checksum, or session
0e5e0c2e 127 * @var int
5b757295 128 */
0e5e0c2e 129 public $_contactID;
5b757295 130
6a488035
TO
131 protected $_userID;
132
133 /**
100fef9d 134 * The Membership ID for membership renewal
6a488035
TO
135 *
136 * @var int
6a488035
TO
137 */
138 public $_membershipId;
139
140 /**
141 * Price Set ID, if the new price set method is used
142 *
143 * @var int
6a488035
TO
144 */
145 public $_priceSetId;
146
147 /**
148 * Array of fields for the price set
149 *
150 * @var array
6a488035
TO
151 */
152 public $_priceSet;
153
154 public $_action;
155
dbddfb08 156 /**
415e7323 157 * Contribution mode.
158 *
159 * In general we are trying to deprecate this parameter but some templates and processors still
160 * require it to denote whether the processor redirects offsite (notify) or not.
161 *
162 * The intent is that this knowledge should not be required and all contributions should
163 * be created in a pending state and updated based on the payment result without needing to be
164 * aware of the processor workings.
165 *
dbddfb08 166 * @var string
415e7323 167 *
168 * @deprecated
dbddfb08
EM
169 */
170 public $_contributeMode;
171
172 /**
100fef9d 173 * Contribution page supports memberships
b67daa72 174 * @var bool
dbddfb08
EM
175 */
176 public $_useForMember;
8ae4d0d3 177
0f2b049e 178 /**
1330f57a 179 * @var bool
0f2b049e 180 * @deprecated
0f2b049e 181 */
8ae4d0d3 182 public $_isBillingAddressRequiredForPayLater;
353ffa53 183
0c7c9ff7
KC
184 /**
185 * Flag if email field exists in embedded profile
186 *
187 * @var bool
188 */
189 public $_emailExists = FALSE;
190
18135422 191 /**
415e7323 192 * Is this a backoffice form.
193 *
194 * Processors may display different options to backoffice users.
195 *
18135422 196 * @var bool
197 */
198 public $isBackOffice = FALSE;
199
200 /**
201 * Payment instrument if for the transaction.
202 *
203 * This will generally be drawn from the payment processor and is ignored for
204 * front end forms.
205 *
206 * @var int
207 */
208 public $paymentInstrumentID;
209
36601c73
MW
210 /**
211 * The contribution ID - is an option in the URL if you are making a payment against an existing contribution (an
212 * "invoice payment").
213 *
214 * @var int
215 */
216 public $_ccid;
217
c59e7960 218 /**
219 * Is the price set quick config.
220 * @return bool
221 */
222 public function isQuickConfig() {
77c21b32 223 return self::$_quickConfig ?? FALSE;
c59e7960 224 }
225
6a488035 226 /**
fe482240 227 * Set variables up before form is built.
6a488035 228 *
7fe37828
EM
229 * @throws \CRM_Contribute_Exception_InactiveContributionPageException
230 * @throws \Exception
6a488035
TO
231 */
232 public function preProcess() {
6a488035
TO
233
234 // current contribution page id
235 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
37e877b2 236 $this->_ccid = CRM_Utils_Request::retrieve('ccid', 'Positive', $this);
6a488035 237 if (!$this->_id) {
d420cf02
DL
238 // seems like the session is corrupted and/or we lost the id trail
239 // lets just bump this to a regular session error and redirect user to main page
240 $this->controller->invalidKeyRedirect();
6a488035 241 }
67c998f4 242 $this->_emailExists = $this->get('emailExists');
d420cf02 243
5b757295 244 // this was used prior to the cleverer this_>getContactID - unsure now
2dbdb9b9 245 $this->_userID = CRM_Core_Session::getLoggedInContactID();
5b757295 246
247 $this->_contactID = $this->_membershipContactID = $this->getContactID();
6a488035 248 $this->_mid = NULL;
5b757295 249 if ($this->_contactID) {
6a488035
TO
250 $this->_mid = CRM_Utils_Request::retrieve('mid', 'Positive', $this);
251 if ($this->_mid) {
252 $membership = new CRM_Member_DAO_Membership();
253 $membership->id = $this->_mid;
254
255 if ($membership->find(TRUE)) {
256 $this->_defaultMemTypeId = $membership->membership_type_id;
5b757295 257 if ($membership->contact_id != $this->_contactID) {
6fe8deba 258 $validMembership = FALSE;
33260076 259 $organizations = CRM_Contact_BAO_Relationship::getPermissionedContacts($this->_userID, NULL, NULL, 'Organization');
260 if (!empty($organizations) && array_key_exists($membership->contact_id, $organizations)) {
6fe8deba
DS
261 $this->_membershipContactID = $membership->contact_id;
262 $this->assign('membershipContactID', $this->_membershipContactID);
33260076 263 $this->assign('membershipContactName', $organizations[$this->_membershipContactID]['name']);
6fe8deba 264 $validMembership = TRUE;
0db6c3e1
TO
265 }
266 else {
51e89def
DS
267 $membershipType = new CRM_Member_BAO_MembershipType();
268 $membershipType->id = $membership->membership_type_id;
269 if ($membershipType->find(TRUE)) {
f9f0eff9 270 // CRM-14051 - membership_type.relationship_type_id is a CTRL-A padded string w one or more ID values.
f92d1e2a 271 // Convert to comma separated list.
f9f0eff9 272 $inheritedRelTypes = implode(CRM_Utils_Array::explodePadded($membershipType->relationship_type_id), ',');
51e89def
DS
273 $permContacts = CRM_Contact_BAO_Relationship::getPermissionedContacts($this->_userID, $membershipType->relationship_type_id);
274 if (array_key_exists($membership->contact_id, $permContacts)) {
275 $this->_membershipContactID = $membership->contact_id;
6fe8deba 276 $validMembership = TRUE;
51e89def
DS
277 }
278 }
6a488035 279 }
6fe8deba
DS
280 if (!$validMembership) {
281 CRM_Core_Session::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Membership Invalid'), 'alert');
282 }
6a488035
TO
283 }
284 }
285 else {
286 CRM_Core_Session::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Membership Invalid'), 'alert');
287 }
288 unset($membership);
289 }
290 }
291
292 // we do not want to display recently viewed items, so turn off
293 $this->assign('displayRecent', FALSE);
6a488035
TO
294
295 // action
296 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
297 $this->assign('action', $this->_action);
298
299 // current mode
300 $this->_mode = ($this->_action == 1024) ? 'test' : 'live';
301
302 $this->_values = $this->get('values');
303 $this->_fields = $this->get('fields');
304 $this->_bltID = $this->get('bltID');
305 $this->_paymentProcessor = $this->get('paymentProcessor');
3dd22219 306
6a488035
TO
307 $this->_priceSetId = $this->get('priceSetId');
308 $this->_priceSet = $this->get('priceSet');
309
310 if (!$this->_values) {
311 // get all the values from the dao object
be2fb01f
CW
312 $this->_values = [];
313 $this->_fields = [];
6a488035
TO
314
315 CRM_Contribute_BAO_ContributionPage::setValues($this->_id, $this->_values);
40c655aa 316 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
66af7c48
PN
317 && !CRM_Core_Permission::check('add contributions of type ' . CRM_Contribute_PseudoConstant::financialType($this->_values['financial_type_id']))
318 ) {
beb414cc 319 CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
0799e1c4 320 }
a7488080 321 if (empty($this->_values['is_active'])) {
4b57bc9f 322 throw new CRM_Contribute_Exception_InactiveContributionPageException(ts('The page you requested is currently unavailable.'), $this->_id);
6a488035
TO
323 }
324
ed1c698a 325 $endDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('end_date', $this->_values));
326 $now = date('YmdHis');
327 if ($endDate && $endDate < $now) {
6dabf459 328 throw new CRM_Contribute_Exception_PastContributionPageException(ts('The page you requested has past its end date on %1', [1 => CRM_Utils_Date::customFormat($endDate)]), $this->_id);
ed1c698a 329 }
330
331 $startDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('start_date', $this->_values));
332 if ($startDate && $startDate > $now) {
6dabf459 333 throw new CRM_Contribute_Exception_FutureContributionPageException(ts('The page you requested will be active from %1', [1 => CRM_Utils_Date::customFormat($startDate)]), $this->_id);
ed1c698a 334 }
335
8345c9d3 336 $this->assignBillingType();
6a488035
TO
337
338 // check for is_monetary status
9c1bc317
CW
339 $isMonetary = $this->_values['is_monetary'] ?? NULL;
340 $isPayLater = $this->_values['is_pay_later'] ?? NULL;
24cf7458 341 if (!empty($this->_ccid)) {
342 $this->_values['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
343 $this->_ccid,
344 'financial_type_id'
345 );
346 if ($isPayLater) {
347 $isPayLater = FALSE;
348 $this->_values['is_pay_later'] = FALSE;
349 }
37e877b2 350 }
bf7ae813 351 if ($isPayLater) {
352 $this->setPayLaterLabel($this->_values['pay_later_text']);
353 }
6a488035 354
427ae6c5
JP
355 if ($isMonetary) {
356 $this->_paymentProcessorIDs = array_filter(explode(
a6c15c46
EM
357 CRM_Core_DAO::VALUE_SEPARATOR,
358 CRM_Utils_Array::value('payment_processor', $this->_values)
427ae6c5 359 ));
f92d1e2a 360
cbcb5b49 361 $this->assignPaymentProcessor($isPayLater);
6a488035
TO
362 }
363
364 // get price info
365 // CRM-5095
d1d16083 366 $priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $this->_id);
367 CRM_Price_BAO_PriceSet::initSet($this, 'civicrm_contribution_page', FALSE, $priceSetId);
6a488035
TO
368
369 // this avoids getting E_NOTICE errors in php
be2fb01f 370 $setNullFields = [
6a488035 371 'amount_block_is_active',
6a488035
TO
372 'is_allow_other_amount',
373 'footer_text',
be2fb01f 374 ];
6a488035
TO
375 foreach ($setNullFields as $f) {
376 if (!isset($this->_values[$f])) {
377 $this->_values[$f] = NULL;
378 }
379 }
380
381 //check if Membership Block is enabled, if Membership Fields are included in profile
382 //get membership section for this contribution page
383 $this->_membershipBlock = CRM_Member_BAO_Membership::getMembershipBlock($this->_id);
384 $this->set('membershipBlock', $this->_membershipBlock);
385
4779abb3 386 if (!empty($this->_values['custom_pre_id'])) {
6a488035
TO
387 $preProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_pre_id']);
388 }
389
4779abb3 390 if (!empty($this->_values['custom_post_id'])) {
6a488035
TO
391 $postProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_post_id']);
392 }
393
9ac53857 394 if (((isset($postProfileType) && $postProfileType === 'Membership') ||
395 (isset($preProfileType) && $preProfileType === 'Membership')
6a488035
TO
396 ) &&
397 !$this->_membershipBlock['is_active']
398 ) {
9ac53857 399 CRM_Core_Error::statusBounce(ts('This page includes a Profile with Membership fields - but the Membership Block is NOT enabled. Please notify the site administrator.'));
6a488035
TO
400 }
401
402 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock::getPledgeBlock($this->_id);
403
404 if ($pledgeBlock) {
9c1bc317
CW
405 $this->_values['pledge_block_id'] = $pledgeBlock['id'] ?? NULL;
406 $this->_values['max_reminders'] = $pledgeBlock['max_reminders'] ?? NULL;
407 $this->_values['initial_reminder_day'] = $pledgeBlock['initial_reminder_day'] ?? NULL;
408 $this->_values['additional_reminder_day'] = $pledgeBlock['additional_reminder_day'] ?? NULL;
6a488035
TO
409
410 //set pledge id in values
411 $pledgeId = CRM_Utils_Request::retrieve('pledgeId', 'Positive', $this);
412
413 //authenticate pledge user for pledge payment.
414 if ($pledgeId) {
415 $this->_values['pledge_id'] = $pledgeId;
416
417 //lets override w/ pledge campaign.
418 $this->_values['campaign_id'] = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge',
419 $pledgeId,
420 'campaign_id'
421 );
422 self::authenticatePledgeUser();
423 }
424 }
425 $this->set('values', $this->_values);
426 $this->set('fields', $this->_fields);
427 }
428
429 // Handle PCP
430 $pcpId = CRM_Utils_Request::retrieve('pcpId', 'Positive', $this);
431 if ($pcpId) {
353ffa53
TO
432 $pcp = CRM_PCP_BAO_PCP::handlePcp($pcpId, 'contribute', $this->_values);
433 $this->_pcpId = $pcp['pcpId'];
6a488035 434 $this->_pcpBlock = $pcp['pcpBlock'];
353ffa53 435 $this->_pcpInfo = $pcp['pcpInfo'];
6a488035
TO
436 }
437
438 // Link (button) for users to create their own Personal Campaign page
439 if ($linkText = CRM_PCP_BAO_PCP::getPcpBlockStatus($this->_id, 'contribute')) {
440 $linkTextUrl = CRM_Utils_System::url('civicrm/contribute/campaign',
441 "action=add&reset=1&pageId={$this->_id}&component=contribute",
442 FALSE, NULL, TRUE
443 );
444 $this->assign('linkTextUrl', $linkTextUrl);
445 $this->assign('linkText', $linkText);
446 }
447
448 //set pledge block if block id is set
a7488080 449 if (!empty($this->_values['pledge_block_id'])) {
6a488035
TO
450 $this->assign('pledgeBlock', TRUE);
451 }
452
f92d1e2a 453 // check if one of the (amount , membership) blocks is active or not.
6a488035
TO
454 $this->_membershipBlock = $this->get('membershipBlock');
455
456 if (!$this->_values['amount_block_is_active'] &&
457 !$this->_membershipBlock['is_active'] &&
458 !$this->_priceSetId
459 ) {
9ac53857 460 CRM_Core_Error::statusBounce(ts('The requested online contribution page is missing a required Contribution Amount section or Membership section or Price Set. Please check with the site administrator for assistance.'));
6a488035
TO
461 }
462
463 if ($this->_values['amount_block_is_active']) {
464 $this->set('amount_block_is_active', $this->_values['amount_block_is_active']);
465 }
466
467 $this->_contributeMode = $this->get('contributeMode');
468 $this->assign('contributeMode', $this->_contributeMode);
469
470 //assigning is_monetary and is_email_receipt to template
471 $this->assign('is_monetary', $this->_values['is_monetary']);
472 $this->assign('is_email_receipt', $this->_values['is_email_receipt']);
473 $this->assign('bltID', $this->_bltID);
474
475 //assign cancelSubscription URL to templates
476 $this->assign('cancelSubscriptionUrl',
477 CRM_Utils_Array::value('cancelSubscriptionUrl', $this->_values)
478 );
479
6489e3de
SL
480 $title = !empty($this->_values['frontend_title']) ? $this->_values['frontend_title'] : $this->_values['title'];
481
482 $this->setTitle(($this->_pcpId ? $this->_pcpInfo['title'] : $title));
be2fb01f 483 $this->_defaults = [];
6a488035
TO
484
485 $this->_amount = $this->get('amount');
d02c6418 486 // Assigning this to the template means it will be passed through to the payment form.
487 // This can, for example, by used by payment processors using client side encryption
488 $this->assign('currency', $this->getCurrency());
6a488035 489
85939a77 490 CRM_Contribute_BAO_Contribution_Utils::overrideDefaultCurrency($this->_values);
6a488035
TO
491
492 //lets allow user to override campaign.
493 $campID = CRM_Utils_Request::retrieve('campID', 'Positive', $this);
494 if ($campID && CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Campaign', $campID)) {
495 $this->_values['campaign_id'] = $campID;
496 }
497
498 //do check for cancel recurring and clean db, CRM-7696
a3d827a7 499 if (CRM_Utils_Request::retrieve('cancel', 'Boolean')) {
6a488035
TO
500 self::cancelRecurring();
501 }
8ae4d0d3 502
503 // check if billing block is required for pay later
f3acfdd9 504 if (!empty($this->_values['is_pay_later'])) {
9c1bc317 505 $this->_isBillingAddressRequiredForPayLater = $this->_values['is_billing_required'] ?? NULL;
8ae4d0d3 506 $this->assign('isBillingAddressRequiredForPayLater', $this->_isBillingAddressRequiredForPayLater);
507 }
6a488035
TO
508 }
509
510 /**
fe482240 511 * Set the default values.
6a488035 512 */
00be9182 513 public function setDefaultValues() {
6a488035
TO
514 return $this->_defaults;
515 }
516
517 /**
fe482240 518 * Assign the minimal set of variables to the template.
6a488035 519 */
00be9182 520 public function assignToTemplate() {
0b50eca0 521 $this->set('name', $this->assignBillingName($this->_params));
6a488035
TO
522
523 $this->assign('paymentProcessor', $this->_paymentProcessor);
be2fb01f 524 $vars = [
353ffa53
TO
525 'amount',
526 'currencyID',
527 'credit_card_type',
528 'trxn_id',
529 'amount_level',
be2fb01f 530 ];
6a488035
TO
531
532 $config = CRM_Core_Config::singleton();
8cc574cf 533 if (isset($this->_values['is_recur']) && !empty($this->_paymentProcessor['is_recur'])) {
6a488035 534 $this->assign('is_recur_enabled', 1);
be2fb01f 535 $vars = array_merge($vars, [
353ffa53
TO
536 'is_recur',
537 'frequency_interval',
538 'frequency_unit',
539 'installments',
be2fb01f 540 ]);
6a488035
TO
541 }
542
543 if (in_array('CiviPledge', $config->enableComponents) &&
544 CRM_Utils_Array::value('is_pledge', $this->_params) == 1
545 ) {
546 $this->assign('pledge_enabled', 1);
547
be2fb01f 548 $vars = array_merge($vars, [
6a488035 549 'is_pledge',
353ffa53
TO
550 'pledge_frequency_interval',
551 'pledge_frequency_unit',
552 'pledge_installments',
be2fb01f 553 ]);
6a488035
TO
554 }
555
c039f658 556 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
557 // function to get correct amount level consistently. Remove setting of the amount level in
558 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
559 // to cover all variants.
6a488035
TO
560 if (isset($this->_params['amount_other']) || isset($this->_params['selectMembership'])) {
561 $this->_params['amount_level'] = '';
562 }
563
564 foreach ($vars as $v) {
3fb990f4 565 if (isset($this->_params[$v])) {
735fe42d
PJ
566 if ($v == "amount" && $this->_params[$v] === 0) {
567 $this->_params[$v] = CRM_Utils_Money::format($this->_params[$v], NULL, NULL, TRUE);
3fb990f4 568 }
6a488035
TO
569 $this->assign($v, $this->_params[$v]);
570 }
571 }
572
0b50eca0 573 $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
574 $this->_params,
575 $this->_bltID
576 ));
6a488035 577
cb804cd9 578 if (!empty($this->_params['onbehalf_profile_id']) && !empty($this->_params['onbehalf'])) {
6a488035
TO
579 $this->assign('onBehalfName', $this->_params['organization_name']);
580 $locTypeId = array_keys($this->_params['onbehalf_location']['email']);
581 $this->assign('onBehalfEmail', $this->_params['onbehalf_location']['email'][$locTypeId[0]]['email']);
582 }
a050fa6b 583 $this->assignPaymentFields();
d90e6c3b 584 $this->assignEmailField();
6a488035
TO
585
586 // also assign the receipt_text
587 if (isset($this->_values['receipt_text'])) {
588 $this->assign('receipt_text', $this->_values['receipt_text']);
589 }
590 }
591
d90e6c3b
JP
592 /**
593 * Assign email variable in the template.
594 */
595 public function assignEmailField() {
596 //If email exist in a profile, the default billing email field is not loaded on the page.
597 //Hence, assign the existing location type email by iterating through the params.
238ea0e4
JP
598 if ($this->_emailExists && empty($this->_params["email-{$this->_bltID}"])) {
599 foreach ($this->_params as $key => $val) {
9ac53857 600 if (substr($key, 0, 6) === 'email-') {
238ea0e4 601 $this->assign('email', $this->_params[$key]);
d90e6c3b 602 break;
238ea0e4
JP
603 }
604 }
605 }
606 else {
607 $this->assign('email', CRM_Utils_Array::value("email-{$this->_bltID}", $this->_params));
608 }
6a488035
TO
609 }
610
611 /**
fe482240 612 * Add the custom fields.
6a488035 613 *
100fef9d
CW
614 * @param int $id
615 * @param string $name
f4aaa82a
EM
616 * @param bool $viewOnly
617 * @param null $profileContactType
f92d1e2a 618 * @param array $fieldTypes
6a488035 619 */
00be9182 620 public function buildCustom($id, $name, $viewOnly = FALSE, $profileContactType = NULL, $fieldTypes = NULL) {
6a488035 621 if ($id) {
da8d9879 622 $contactID = $this->getContactID();
6a488035
TO
623
624 // we don't allow conflicting fields to be
625 // configured via profile - CRM 2100
be2fb01f 626 $fieldsToIgnore = [
6a488035
TO
627 'receive_date' => 1,
628 'trxn_id' => 1,
629 'invoice_id' => 1,
630 'net_amount' => 1,
631 'fee_amount' => 1,
632 'non_deductible_amount' => 1,
633 'total_amount' => 1,
634 'amount_level' => 1,
635 'contribution_status_id' => 1,
7bc1d4da 636 // @todo replace payment_instrument with payment instrument id.
637 // both are available now but the id field is the most consistent.
6a488035 638 'payment_instrument' => 1,
7bc1d4da 639 'payment_instrument_id' => 1,
640 'contribution_check_number' => 1,
6a488035 641 'financial_type' => 1,
be2fb01f 642 ];
6a488035 643
423b9af4 644 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD, NULL, NULL, FALSE,
645 NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL
646 );
6a488035
TO
647
648 if ($fields) {
0c7c9ff7
KC
649 // determine if email exists in profile so we know if we need to manually insert CRM-2888, CRM-15067
650 foreach ($fields as $key => $field) {
651 if (substr($key, 0, 6) == 'email-' &&
be2fb01f 652 !in_array($profileContactType, ['honor', 'onbehalf'])
0c7c9ff7
KC
653 ) {
654 $this->_emailExists = TRUE;
67c998f4 655 $this->set('emailExists', TRUE);
6a488035
TO
656 }
657 }
658
659 if (array_intersect_key($fields, $fieldsToIgnore)) {
660 $fields = array_diff_key($fields, $fieldsToIgnore);
661 CRM_Core_Session::setStatus(ts('Some of the profile fields cannot be configured for this page.'), ts('Warning'), 'alert');
662 }
663
d7d630be 664 //remove common fields only if profile is not configured for onbehalf/honor
be2fb01f 665 if (!in_array($profileContactType, ['honor', 'onbehalf'])) {
94e01524 666 $fields = array_diff_key($fields, $this->_fields);
d7d630be 667 }
6a488035
TO
668
669 CRM_Core_BAO_Address::checkContactSharedAddressFields($fields, $contactID);
670 $addCaptcha = FALSE;
f3726153 671 // fetch file preview when not submitted yet, like in online contribution Confirm and ThankYou page
be2fb01f 672 $viewOnlyFileValues = empty($profileContactType) ? [] : [$profileContactType => []];
6a488035
TO
673 foreach ($fields as $key => $field) {
674 if ($viewOnly &&
675 isset($field['data_type']) &&
676 $field['data_type'] == 'File' || ($viewOnly && $field['name'] == 'image_URL')
677 ) {
c2292dbd 678 //retrieve file value from submitted values on basis of $profileContactType
9c1bc317 679 $fileValue = $this->_params[$key] ?? NULL;
9b7bedc5 680 if (!empty($profileContactType) && !empty($this->_params[$profileContactType])) {
9c1bc317 681 $fileValue = $this->_params[$profileContactType][$key] ?? NULL;
9b7bedc5 682 }
c2292dbd 683
684 if ($fileValue) {
9c1bc317
CW
685 $path = $fileValue['name'] ?? NULL;
686 $fileType = $fileValue['type'] ?? NULL;
c2292dbd 687 $fileValue = CRM_Utils_File::getFileURL($path, $fileType);
f3726153 688 }
6a488035 689
c2292dbd 690 // format custom file value fetched from submitted value
691 if ($profileContactType) {
692 $viewOnlyFileValues[$profileContactType][$key] = $fileValue;
693 }
694 else {
695 $viewOnlyFileValues[$key] = $fileValue;
696 }
1aedfc98 697
698 // On viewOnly use-case (as in online contribution Confirm page) we no longer need to set
699 // required property because being required file is already uploaded while registration
700 $field['is_required'] = FALSE;
c2292dbd 701 }
133e2c99 702 if ($profileContactType) {
703 //Since we are showing honoree name separately so we are removing it from honoree profile just for display
c043358f 704 if ($profileContactType == 'honor') {
be2fb01f 705 $honoreeNamefields = [
c043358f 706 'prefix_id',
707 'first_name',
708 'last_name',
709 'suffix_id',
710 'organization_name',
711 'household_name',
be2fb01f 712 ];
c043358f 713 if (in_array($field['name'], $honoreeNamefields)) {
714 unset($fields[$field['name']]);
715 continue;
716 }
133e2c99 717 }
6a488035
TO
718 if (!empty($fieldTypes) && in_array($field['field_type'], $fieldTypes)) {
719 CRM_Core_BAO_UFGroup::buildProfile(
720 $this,
721 $field,
722 CRM_Profile_Form::MODE_CREATE,
723 $contactID,
133e2c99 724 TRUE,
725 $profileContactType
6a488035 726 );
133e2c99 727 $this->_fields[$profileContactType][$key] = $field;
6a488035
TO
728 }
729 else {
730 unset($fields[$key]);
731 }
732 }
733 else {
734 CRM_Core_BAO_UFGroup::buildProfile(
735 $this,
736 $field,
737 CRM_Profile_Form::MODE_CREATE,
738 $contactID,
739 TRUE
740 );
741 $this->_fields[$key] = $field;
742 }
71fc6ea4
DG
743 // CRM-11316 Is ReCAPTCHA enabled for this profile AND is this an anonymous visitor
744 if ($field['add_captcha'] && !$this->_userID) {
6a488035
TO
745 $addCaptcha = TRUE;
746 }
747 }
748
749 $this->assign($name, $fields);
750
6d43e496 751 if ($profileContactType && count($viewOnlyFileValues[$profileContactType])) {
752 $this->assign('viewOnlyPrefixFileValues', $viewOnlyFileValues);
753 }
754 elseif (count($viewOnlyFileValues)) {
f3726153 755 $this->assign('viewOnlyFileValues', $viewOnlyFileValues);
756 }
757
6a488035 758 if ($addCaptcha && !$viewOnly) {
96ea60e0 759 $this->enableCaptchaOnForm();
6a488035
TO
760 }
761 }
762 }
763 }
764
96ea60e0
AP
765 /**
766 * Enable ReCAPTCHA on Contribution form
767 */
768 protected function enableCaptchaOnForm() {
268ff0e8 769 CRM_Utils_ReCAPTCHA::enableCaptchaOnForm($this);
ce287b85
AP
770 }
771
9ac53857 772 /**
773 * Assign payment field information to the template.
774 *
775 * @throws \CRM_Core_Exception
776 * @throws \CiviCRM_API3_Exception
777 */
a050fa6b
MWMC
778 public function assignPaymentFields() {
779 //fix for CRM-3767
780 $isMonetary = FALSE;
781 if ($this->_amount > 0.0) {
782 $isMonetary = TRUE;
783 }
784 elseif (!empty($this->_params['selectMembership'])) {
785 $memFee = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params['selectMembership'], 'minimum_fee');
786 if ($memFee > 0.0) {
787 $isMonetary = TRUE;
788 }
789 }
790
791 // The concept of contributeMode is deprecated.
792 // The payment processor object can provide info about the fields it shows.
793 if ($isMonetary && is_a($this->_paymentProcessor['object'], 'CRM_Core_Payment')) {
9ac53857 794 /** @var \CRM_Core_Payment $paymentProcessorObject */
a050fa6b
MWMC
795 $paymentProcessorObject = $this->_paymentProcessor['object'];
796
797 $paymentFields = $paymentProcessorObject->getPaymentFormFields();
798 foreach ($paymentFields as $index => $paymentField) {
799 if (!isset($this->_params[$paymentField])) {
800 unset($paymentFields[$index]);
801 continue;
802 }
803 if ($paymentField === 'credit_card_exp_date') {
804 $date = CRM_Utils_Date::format(CRM_Utils_Array::value('credit_card_exp_date', $this->_params));
805 $date = CRM_Utils_Date::mysqlToIso($date);
806 $this->assign('credit_card_exp_date', $date);
807 }
808 elseif ($paymentField === 'credit_card_number') {
809 $this->assign('credit_card_number',
810 CRM_Utils_System::mungeCreditCard(CRM_Utils_Array::value('credit_card_number', $this->_params))
811 );
812 }
813 elseif ($paymentField === 'credit_card_type') {
814 $this->assign('credit_card_type', CRM_Core_PseudoConstant::getLabel(
815 'CRM_Core_BAO_FinancialTrxn',
816 'card_type_id',
817 CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $this->_params['credit_card_type'])
818 ));
819 }
820 else {
821 $this->assign($paymentField, $this->_params[$paymentField]);
822 }
823 }
824 $this->assign('paymentFieldsetLabel', CRM_Core_Payment_Form::getPaymentLabel($paymentProcessorObject));
825 $this->assign('paymentFields', $paymentFields);
826
827 }
828 }
829
ce287b85
AP
830 /**
831 * Display ReCAPTCHA warning on Contribution form
832 */
833 protected function displayCaptchaWarning() {
834 if (CRM_Core_Permission::check("administer CiviCRM")) {
268ff0e8 835 if (!CRM_Utils_ReCAPTCHA::hasSettingsAvailable()) {
ce287b85
AP
836 $this->assign('displayCaptchaWarning', TRUE);
837 }
8237b510 838 }
96ea60e0
AP
839 }
840
ce287b85
AP
841 /**
842 * Check if ReCAPTCHA has to be added on Contribution form forcefully.
843 */
844 protected function hasToAddForcefully() {
268ff0e8 845 return CRM_Utils_ReCAPTCHA::hasToAddForcefully();
ce287b85
AP
846 }
847
4779abb3 848 /**
849 * Add onbehalf/honoree profile fields and native module fields.
850 *
851 * @param int $id
852 * @param CRM_Core_Form $form
9ac53857 853 *
5903c058 854 * @throws \API_Exception
9ac53857 855 * @throws \CRM_Core_Exception
5903c058 856 * @throws \CiviCRM_API3_Exception
4779abb3 857 */
5903c058 858 public function buildComponentForm($id, $form): void {
bcb8cc84 859 if (empty($id)) {
860 return;
861 }
862
863 $contactID = $this->getContactID();
864
be2fb01f 865 foreach (['soft_credit', 'on_behalf'] as $module) {
9ac53857 866 if ($module === 'soft_credit') {
4779abb3 867 if (empty($form->_values['honoree_profile_id'])) {
868 continue;
869 }
bcb8cc84 870
4779abb3 871 if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $form->_values['honoree_profile_id'], 'is_active')) {
9ac53857 872 CRM_Core_Error::statusBounce(ts('This contribution page has been configured for contribution on behalf of honoree and the selected honoree profile is either disabled or not found.'));
bcb8cc84 873 }
874
4779abb3 875 $profileContactType = CRM_Core_BAO_UFGroup::getContactType($form->_values['honoree_profile_id']);
be2fb01f
CW
876 $requiredProfileFields = [
877 'Individual' => ['first_name', 'last_name'],
878 'Organization' => ['organization_name', 'email'],
879 'Household' => ['household_name', 'email'],
880 ];
4779abb3 881 $validProfile = CRM_Core_BAO_UFGroup::checkValidProfile($form->_values['honoree_profile_id'], $requiredProfileFields[$profileContactType]);
bcb8cc84 882 if (!$validProfile) {
9ac53857 883 CRM_Core_Error::statusBounce(ts('This contribution page has been configured for contribution on behalf of honoree and the required fields of the selected honoree profile are disabled or doesn\'t exist.'));
bcb8cc84 884 }
885
be2fb01f 886 foreach (['honor_block_title', 'honor_block_text'] as $name) {
4779abb3 887 $form->assign($name, $form->_values[$name]);
cb804cd9 888 }
889
890 $softCreditTypes = CRM_Core_OptionGroup::values("soft_credit_type", FALSE);
891
892 // radio button for Honor Type
4779abb3 893 foreach ($form->_values['soft_credit_types'] as $value) {
ca5603d5 894 $honorTypes[$value] = $softCreditTypes[$value];
cb804cd9 895 }
ca5603d5 896 $form->addRadio('soft_credit_type_id', NULL, $honorTypes, ['allowClear' => TRUE]);
cb804cd9 897
4779abb3 898 $honoreeProfileFields = CRM_Core_BAO_UFGroup::getFields(
899 $this->_values['honoree_profile_id'], FALSE,
900 NULL, NULL,
901 NULL, FALSE,
902 NULL, TRUE,
903 NULL, CRM_Core_Permission::CREATE
cb804cd9 904 );
cb804cd9 905 $form->assign('honoreeProfileFields', $honoreeProfileFields);
906
907 // add the form elements
908 foreach ($honoreeProfileFields as $name => $field) {
909 // If soft credit type is not chosen then make omit requiredness from honoree profile fields
910 if (count($form->_submitValues) &&
911 empty($form->_submitValues['soft_credit_type_id']) &&
912 !empty($field['is_required'])
913 ) {
914 $field['is_required'] = FALSE;
915 }
c043358f 916 CRM_Core_BAO_UFGroup::buildProfile($form, $field, CRM_Profile_Form::MODE_CREATE, NULL, FALSE, FALSE, NULL, 'honor');
cb804cd9 917 }
bcb8cc84 918 }
919 else {
4779abb3 920 if (empty($form->_values['onbehalf_profile_id'])) {
921 continue;
922 }
bcb8cc84 923
4779abb3 924 if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $form->_values['onbehalf_profile_id'], 'is_active')) {
9ac53857 925 CRM_Core_Error::statusBounce(ts('This contribution page has been configured for contribution on behalf of an organization and the selected onbehalf profile is either disabled or not found.'));
bcb8cc84 926 }
927
928 $member = CRM_Member_BAO_Membership::getMembershipBlock($form->_id);
929 if (empty($member['is_active'])) {
930 $msg = ts('Mixed profile not allowed for on behalf of registration/sign up.');
4779abb3 931 $onBehalfProfile = CRM_Core_BAO_UFGroup::profileGroups($form->_values['onbehalf_profile_id']);
0c7c9ff7 932 foreach (
be2fb01f 933 [
bcb8cc84 934 'Individual',
935 'Organization',
936 'Household',
be2fb01f 937 ] as $contactType
0c7c9ff7 938 ) {
bcb8cc84 939 if (in_array($contactType, $onBehalfProfile) &&
940 (in_array('Membership', $onBehalfProfile) ||
941 in_array('Contribution', $onBehalfProfile)
942 )
943 ) {
9ac53857 944 CRM_Core_Error::statusBounce($msg);
bcb8cc84 945 }
946 }
947 }
948
c043358f 949 if ($contactID) {
33260076 950 // retrieve all permissioned organizations of contact $contactID
951 $organizations = CRM_Contact_BAO_Relationship::getPermissionedContacts($contactID, NULL, NULL, 'Organization');
c043358f 952
33260076 953 if (count($organizations)) {
c043358f 954 // Related org url - pass checksum if needed
be2fb01f 955 $args = [
4779abb3 956 'ufId' => $form->_values['onbehalf_profile_id'],
f23093b2 957 'cid' => '',
be2fb01f 958 ];
c043358f 959 if (!empty($_GET['cs'])) {
be2fb01f 960 $args = [
4779abb3 961 'ufId' => $form->_values['onbehalf_profile_id'],
c043358f 962 'uid' => $this->_contactID,
963 'cs' => $_GET['cs'],
964 'cid' => '',
be2fb01f 965 ];
c043358f 966 }
967 $locDataURL = CRM_Utils_System::url('civicrm/ajax/permlocation', $args, FALSE, NULL, FALSE);
968 $form->assign('locDataURL', $locDataURL);
969 }
33260076 970 if (count($organizations) > 0) {
971 $form->add('select', 'onbehalfof_id', '', CRM_Utils_Array::collect('name', $organizations));
c043358f 972
be2fb01f 973 $orgOptions = [
c043358f 974 0 => ts('Select an existing organization'),
975 1 => ts('Enter a new organization'),
be2fb01f 976 ];
c043358f 977 $form->addRadio('org_option', ts('options'), $orgOptions);
be2fb01f 978 $form->setDefaults(['org_option' => 0]);
c043358f 979 }
bcb8cc84 980 }
981
5903c058 982 $form->assign('fieldSetTitle', CRM_Core_BAO_UFGroup::getFrontEndTitle($form->_values['onbehalf_profile_id']));
c043358f 983
f3acfdd9 984 if (!empty($form->_values['is_for_organization'])) {
4779abb3 985 if ($form->_values['is_for_organization'] == 2) {
c043358f 986 $form->assign('onBehalfRequired', TRUE);
bcb8cc84 987 }
988 else {
989 $form->addElement('checkbox', 'is_for_organization',
990 $form->_values['for_organization'],
991 NULL
992 );
993 }
994 }
c043358f 995
4779abb3 996 $profileFields = CRM_Core_BAO_UFGroup::getFields(
997 $form->_values['onbehalf_profile_id'],
998 FALSE, CRM_Core_Action::VIEW, NULL,
999 NULL, FALSE, NULL, FALSE, NULL,
1000 CRM_Core_Permission::CREATE, NULL
c043358f 1001 );
4779abb3 1002
c043358f 1003 $form->assign('onBehalfOfFields', $profileFields);
1004 if (!empty($form->_submitValues['onbehalf'])) {
1005 if (!empty($form->_submitValues['onbehalfof_id'])) {
1006 $form->assign('submittedOnBehalf', $form->_submitValues['onbehalfof_id']);
1007 }
d425f39b 1008 $form->assign('submittedOnBehalfInfo', json_encode(str_replace('"', '\"', $form->_submitValues['onbehalf']), JSON_HEX_APOS));
c043358f 1009 }
1010
be2fb01f 1011 $fieldTypes = ['Contact', 'Organization'];
a6a083d8 1012 if (!empty($form->_membershipBlock)) {
be2fb01f 1013 $fieldTypes = array_merge($fieldTypes, ['Membership']);
a6a083d8 1014 }
c043358f 1015 $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization');
1016 $fieldTypes = array_merge($fieldTypes, $contactSubType);
1017
1018 foreach ($profileFields as $name => $field) {
1019 if (in_array($field['field_type'], $fieldTypes)) {
5903c058 1020 [$prefixName, $index] = CRM_Utils_System::explode('-', $name, 2);
be2fb01f 1021 if (in_array($prefixName, ['organization_name', 'email']) && empty($field['is_required'])) {
c043358f 1022 $field['is_required'] = 1;
1023 }
1024 if (count($form->_submitValues) &&
1025 empty($form->_submitValues['is_for_organization']) &&
4779abb3 1026 $form->_values['is_for_organization'] == 1 &&
c043358f 1027 !empty($field['is_required'])
1028 ) {
1029 $field['is_required'] = FALSE;
1030 }
4779abb3 1031 CRM_Core_BAO_UFGroup::buildProfile($form, $field, NULL, NULL, FALSE, 'onbehalf', NULL, 'onbehalf');
c043358f 1032 }
1033 }
bcb8cc84 1034 }
1035 }
1036
1037 }
1038
f4aaa82a 1039 /**
fe482240 1040 * Check template file exists.
f92d1e2a
EM
1041 *
1042 * @param string $suffix
f4aaa82a
EM
1043 *
1044 * @return null|string
1045 */
00be9182 1046 public function checkTemplateFileExists($suffix = NULL) {
6a488035
TO
1047 if ($this->_id) {
1048 $templateFile = "CRM/Contribute/Form/Contribution/{$this->_id}/{$this->_name}.{$suffix}tpl";
1049 $template = CRM_Core_Form::getTemplate();
1050 if ($template->template_exists($templateFile)) {
1051 return $templateFile;
1052 }
1053 }
1054 return NULL;
1055 }
1056
186c9c17 1057 /**
fe482240 1058 * Use the form name to create the tpl file name.
186c9c17
EM
1059 *
1060 * @return string
186c9c17 1061 */
00be9182 1062 public function getTemplateFileName() {
6a488035 1063 $fileName = $this->checkTemplateFileExists();
9ac53857 1064 return $fileName ?: parent::getTemplateFileName();
6a488035
TO
1065 }
1066
186c9c17 1067 /**
f92d1e2a
EM
1068 * Add the extra.tpl in.
1069 *
186c9c17 1070 * Default extra tpl file basically just replaces .tpl with .extra.tpl
f92d1e2a 1071 * i.e. we do not override - why isn't this done at the CRM_Core_Form level?
186c9c17
EM
1072 *
1073 * @return string
186c9c17 1074 */
00be9182 1075 public function overrideExtraTemplateFileName() {
6a488035
TO
1076 $fileName = $this->checkTemplateFileExists('extra.');
1077 return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
1078 }
1079
1080 /**
100fef9d 1081 * Authenticate pledge user during online payment.
9ac53857 1082 *
1083 * @throws \CRM_Core_Exception
6a488035
TO
1084 */
1085 public function authenticatePledgeUser() {
1086 //get the userChecksum and contact id
1087 $userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this);
1088 $contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
1089
1090 //get pledge status and contact id
be2fb01f
CW
1091 $pledgeValues = [];
1092 $pledgeParams = ['id' => $this->_values['pledge_id']];
1093 $returnProperties = ['contact_id', 'status_id'];
6a488035
TO
1094 CRM_Core_DAO::commonRetrieve('CRM_Pledge_DAO_Pledge', $pledgeParams, $pledgeValues, $returnProperties);
1095
1096 //get all status
1097 $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
be2fb01f 1098 $validStatus = [
353ffa53 1099 array_search('Pending', $allStatus),
6a488035
TO
1100 array_search('In Progress', $allStatus),
1101 array_search('Overdue', $allStatus),
be2fb01f 1102 ];
6a488035
TO
1103
1104 $validUser = FALSE;
1105 if ($this->_userID &&
1106 $this->_userID == $pledgeValues['contact_id']
1107 ) {
1108 //check for authenticated user.
1109 $validUser = TRUE;
1110 }
1111 elseif ($userChecksum && $pledgeValues['contact_id']) {
1112 //check for anonymous user.
1113 $validUser = CRM_Contact_BAO_Contact_Utils::validChecksum($pledgeValues['contact_id'], $userChecksum);
1114
1115 //make sure cid is same as pledge contact id
1116 if ($validUser && ($pledgeValues['contact_id'] != $contactID)) {
1117 $validUser = FALSE;
1118 }
1119 }
1120
1121 if (!$validUser) {
9ac53857 1122 CRM_Core_Error::statusBounce(ts("Oops. It looks like you have an incorrect or incomplete link (URL). Please make sure you've copied the entire link, and try again. Contact the site administrator if this error persists."));
6a488035
TO
1123 }
1124
1125 //check for valid pledge status.
1126 if (!in_array($pledgeValues['status_id'], $validStatus)) {
9ac53857 1127 CRM_Core_Error::statusBounce(ts('Oops. You cannot make a payment for this pledge - pledge status is %1.', [1 => CRM_Utils_Array::value($pledgeValues['status_id'], $allStatus)]));
6a488035
TO
1128 }
1129 }
1130
1131 /**
f92d1e2a
EM
1132 * Cancel recurring contributions.
1133 *
6a488035
TO
1134 * In case user cancel recurring contribution,
1135 * When we get the control back from payment gate way
1136 * lets delete the recurring and related contribution.
9ac53857 1137 *
1138 * @throws \CRM_Core_Exception
389bcebf 1139 */
6a488035 1140 public function cancelRecurring() {
a3d827a7 1141 $isCancel = CRM_Utils_Request::retrieve('cancel', 'Boolean');
6a488035 1142 if ($isCancel) {
a3d827a7
CW
1143 $isRecur = CRM_Utils_Request::retrieve('isRecur', 'Boolean');
1144 $recurId = CRM_Utils_Request::retrieve('recurId', 'Positive');
6a488035
TO
1145 //clean db for recurring contribution.
1146 if ($isRecur && $recurId) {
1147 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($recurId);
1148 }
a3d827a7 1149 $contribId = CRM_Utils_Request::retrieve('contribId', 'Positive');
6a488035
TO
1150 if ($contribId) {
1151 CRM_Contribute_BAO_Contribution::deleteContribution($contribId);
1152 }
1153 }
1154 }
96025800 1155
90102a32
EM
1156 /**
1157 * Determine if recurring parameters need to be added to the form parameters.
8cb12ff1 1158 *
90102a32
EM
1159 * - is_recur
1160 * - frequency_interval
1161 * - frequency_unit
1162 *
1163 * For membership this is based on the membership type.
1164 *
1165 * This needs to be done before processing the pre-approval redirect where relevant on the main page or before any payment processing.
1166 *
1167 * Arguably the form should start to build $this->_params in the pre-process main page & use that array consistently throughout.
1168 */
1169 protected function setRecurringMembershipParams() {
9c1bc317 1170 $selectedMembershipTypeID = $this->_params['selectMembership'] ?? NULL;
8cb12ff1 1171 if ($selectedMembershipTypeID) {
fd359255
EM
1172 // @todo the price_x fields will ALWAYS allow us to determine the membership - so we should ignore
1173 // 'selectMembership' and calculate from the price_x fields so we have one method that always works
1174 // this is lazy & only catches when selectMembership is set, but the worst of all worlds would be to fix
1175 // this with an else (calculate for price set).
8cb12ff1 1176 $membershipTypes = CRM_Price_BAO_PriceSet::getMembershipTypesFromPriceSet($this->_priceSetId);
1177 if (in_array($selectedMembershipTypeID, $membershipTypes['autorenew_required'])
1178 || (in_array($selectedMembershipTypeID, $membershipTypes['autorenew_optional']) &&
1179 !empty($this->_params['is_recur']))
1180 ) {
fd359255
EM
1181 $this->_params['auto_renew'] = TRUE;
1182 }
1183 }
8cb12ff1 1184 if ((!empty($this->_params['selectMembership']) || !empty($this->_params['priceSetId']))
1185 && !empty($this->_paymentProcessor['is_recur']) &&
b99f3e96 1186 !empty($this->_params['auto_renew'])
8cb12ff1 1187 && empty($this->_params['is_recur']) && empty($this->_params['frequency_interval'])
90102a32
EM
1188 ) {
1189
1190 $this->_params['is_recur'] = $this->_values['is_recur'] = 1;
1191 // check if price set is not quick config
1192 if (!empty($this->_params['priceSetId']) && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params['priceSetId'], 'is_quick_config')) {
96ecdef5 1193 list($this->_params['frequency_interval'], $this->_params['frequency_unit']) = CRM_Price_BAO_PriceSet::getRecurDetails($this->_params['priceSetId']);
90102a32
EM
1194 }
1195 else {
1196 // FIXME: set interval and unit based on selected membership type
1197 $this->_params['frequency_interval'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
1198 $this->_params['selectMembership'], 'duration_interval'
1199 );
1200 $this->_params['frequency_unit'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
1201 $this->_params['selectMembership'], 'duration_unit'
1202 );
1203 }
1204 }
1205 }
1206
e364c762 1207 /**
1208 * Get the payment processor object for the submission, returning the manual one for offline payments.
1209 *
1210 * @return CRM_Core_Payment
1211 */
1212 protected function getPaymentProcessorObject() {
1213 if (!empty($this->_paymentProcessor)) {
1214 return $this->_paymentProcessor['object'];
1215 }
1216 return new CRM_Core_Payment_Manual();
1217 }
1218
ec57bf87 1219 /**
1220 * Get the amount for the main contribution.
1221 *
1222 * The goal is to expand this function so that all the argy-bargy of figuring out the amount
1223 * winds up here as the main spaghetti shrinks.
1224 *
1225 * If there is a separate membership contribution this is the 'other one'. Otherwise there
1226 * is only one.
1227 *
1228 * @param $params
1229 *
1230 * @return float
1231 *
1232 * @throws \CiviCRM_API3_Exception
1233 */
1234 protected function getMainContributionAmount($params) {
1235 if (!empty($params['selectMembership'])) {
1236 if (empty($params['amount']) && !$this->_separateMembershipPayment) {
1237 return CRM_Member_BAO_MembershipType::getMembershipType($params['selectMembership'])['minimum_fee'] ?? 0;
1238 }
1239 }
1240 return $params['amount'] ?? 0;
1241 }
1242
bdcbbfea 1243 /**
1244 * Wrapper for processAmount that also sets autorenew.
1245 *
1246 * @param $fields
1247 * This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
1248 * And, it would make sense to introduce caching into that function and call it from here rather than
1249 * require the $fields array which is passed from pillar to post around the form in order to pass it in here.
1250 * @param array $params
1251 * Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
1252 * @param $lineItems
1253 * Line item array to be altered.
1254 * @param int $priceSetID
1255 */
1256 public function processAmountAndGetAutoRenew($fields, &$params, &$lineItems, $priceSetID = NULL) {
1257 CRM_Price_BAO_PriceSet::processAmount($fields, $params, $lineItems, $priceSetID);
1258 $autoRenew = [];
1259 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
1260 foreach ($lineItems as $lineItem) {
1261 if (!empty($lineItem['auto_renew']) &&
1262 is_numeric($lineItem['auto_renew'])
1263 ) {
1264 $autoRenew[$lineItem['auto_renew']] += $lineItem['line_total'];
1265 }
1266 }
1267 if (count($autoRenew) > 1) {
1268 $params['autoRenew'] = $autoRenew;
1269 }
1270 }
1271
6a488035 1272}