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