Merge pull request #17700 from ixiam/dev-#1843
[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 e.g express for payment express, notify for off-site + notification back to CiviCRM
158 * @var string
159 */
160 public $_contributeMode;
161
162 /**
163 * Contribution page supports memberships
164 * @var bool
165 */
166 public $_useForMember;
167
168 /**
169 * @var bool
170 * @deprecated
171 */
172 public $_isBillingAddressRequiredForPayLater;
173
174 /**
175 * Flag if email field exists in embedded profile
176 *
177 * @var bool
178 */
179 public $_emailExists = FALSE;
180
181 /**
182 * Is this a backoffice form
183 * (this will affect whether paypal express code is displayed)
184 * @var bool
185 */
186 public $isBackOffice = FALSE;
187
188 /**
189 * Payment instrument if for the transaction.
190 *
191 * This will generally be drawn from the payment processor and is ignored for
192 * front end forms.
193 *
194 * @var int
195 */
196 public $paymentInstrumentID;
197
198 /**
199 * Is the price set quick config.
200 * @return bool
201 */
202 public function isQuickConfig() {
203 return self::$_quickConfig ?? FALSE;
204 }
205
206 /**
207 * Set variables up before form is built.
208 *
209 * @throws \CRM_Contribute_Exception_InactiveContributionPageException
210 * @throws \Exception
211 */
212 public function preProcess() {
213
214 // current contribution page id
215 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
216 $this->_ccid = CRM_Utils_Request::retrieve('ccid', 'Positive', $this);
217 if (!$this->_id) {
218 // seems like the session is corrupted and/or we lost the id trail
219 // lets just bump this to a regular session error and redirect user to main page
220 $this->controller->invalidKeyRedirect();
221 }
222 $this->_emailExists = $this->get('emailExists');
223
224 // this was used prior to the cleverer this_>getContactID - unsure now
225 $this->_userID = CRM_Core_Session::getLoggedInContactID();
226
227 $this->_contactID = $this->_membershipContactID = $this->getContactID();
228 $this->_mid = NULL;
229 if ($this->_contactID) {
230 $this->_mid = CRM_Utils_Request::retrieve('mid', 'Positive', $this);
231 if ($this->_mid) {
232 $membership = new CRM_Member_DAO_Membership();
233 $membership->id = $this->_mid;
234
235 if ($membership->find(TRUE)) {
236 $this->_defaultMemTypeId = $membership->membership_type_id;
237 if ($membership->contact_id != $this->_contactID) {
238 $validMembership = FALSE;
239 $organizations = CRM_Contact_BAO_Relationship::getPermissionedContacts($this->_userID, NULL, NULL, 'Organization');
240 if (!empty($organizations) && array_key_exists($membership->contact_id, $organizations)) {
241 $this->_membershipContactID = $membership->contact_id;
242 $this->assign('membershipContactID', $this->_membershipContactID);
243 $this->assign('membershipContactName', $organizations[$this->_membershipContactID]['name']);
244 $validMembership = TRUE;
245 }
246 else {
247 $membershipType = new CRM_Member_BAO_MembershipType();
248 $membershipType->id = $membership->membership_type_id;
249 if ($membershipType->find(TRUE)) {
250 // CRM-14051 - membership_type.relationship_type_id is a CTRL-A padded string w one or more ID values.
251 // Convert to comma separated list.
252 $inheritedRelTypes = implode(CRM_Utils_Array::explodePadded($membershipType->relationship_type_id), ',');
253 $permContacts = CRM_Contact_BAO_Relationship::getPermissionedContacts($this->_userID, $membershipType->relationship_type_id);
254 if (array_key_exists($membership->contact_id, $permContacts)) {
255 $this->_membershipContactID = $membership->contact_id;
256 $validMembership = TRUE;
257 }
258 }
259 }
260 if (!$validMembership) {
261 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');
262 }
263 }
264 }
265 else {
266 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');
267 }
268 unset($membership);
269 }
270 }
271
272 // we do not want to display recently viewed items, so turn off
273 $this->assign('displayRecent', FALSE);
274
275 // action
276 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
277 $this->assign('action', $this->_action);
278
279 // current mode
280 $this->_mode = ($this->_action == 1024) ? 'test' : 'live';
281
282 $this->_values = $this->get('values');
283 $this->_fields = $this->get('fields');
284 $this->_bltID = $this->get('bltID');
285 $this->_paymentProcessor = $this->get('paymentProcessor');
286
287 $this->_priceSetId = $this->get('priceSetId');
288 $this->_priceSet = $this->get('priceSet');
289
290 if (!$this->_values) {
291 // get all the values from the dao object
292 $this->_values = [];
293 $this->_fields = [];
294
295 CRM_Contribute_BAO_ContributionPage::setValues($this->_id, $this->_values);
296 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
297 && !CRM_Core_Permission::check('add contributions of type ' . CRM_Contribute_PseudoConstant::financialType($this->_values['financial_type_id']))
298 ) {
299 CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
300 }
301 if (empty($this->_values['is_active'])) {
302 throw new CRM_Contribute_Exception_InactiveContributionPageException(ts('The page you requested is currently unavailable.'), $this->_id);
303 }
304
305 $endDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('end_date', $this->_values));
306 $now = date('YmdHis');
307 if ($endDate && $endDate < $now) {
308 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);
309 }
310
311 $startDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('start_date', $this->_values));
312 if ($startDate && $startDate > $now) {
313 throw new CRM_Contribute_Exception_FutureContributionPageException(ts('The page you requested will be active from %1', [1 => CRM_Utils_Date::customFormat($startDate)]), $this->_id);
314 }
315
316 $this->assignBillingType();
317
318 // check for is_monetary status
319 $isMonetary = $this->_values['is_monetary'] ?? NULL;
320 $isPayLater = $this->_values['is_pay_later'] ?? NULL;
321 if (!empty($this->_ccid)) {
322 $this->_values['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
323 $this->_ccid,
324 'financial_type_id'
325 );
326 if ($isPayLater) {
327 $isPayLater = FALSE;
328 $this->_values['is_pay_later'] = FALSE;
329 }
330 }
331 if ($isPayLater) {
332 $this->setPayLaterLabel($this->_values['pay_later_text']);
333 }
334
335 if ($isMonetary) {
336 $this->_paymentProcessorIDs = array_filter(explode(
337 CRM_Core_DAO::VALUE_SEPARATOR,
338 CRM_Utils_Array::value('payment_processor', $this->_values)
339 ));
340
341 $this->assignPaymentProcessor($isPayLater);
342 }
343
344 // get price info
345 // CRM-5095
346 $priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $this->_id);
347 CRM_Price_BAO_PriceSet::initSet($this, 'civicrm_contribution_page', FALSE, $priceSetId);
348
349 // this avoids getting E_NOTICE errors in php
350 $setNullFields = [
351 'amount_block_is_active',
352 'is_allow_other_amount',
353 'footer_text',
354 ];
355 foreach ($setNullFields as $f) {
356 if (!isset($this->_values[$f])) {
357 $this->_values[$f] = NULL;
358 }
359 }
360
361 //check if Membership Block is enabled, if Membership Fields are included in profile
362 //get membership section for this contribution page
363 $this->_membershipBlock = CRM_Member_BAO_Membership::getMembershipBlock($this->_id);
364 $this->set('membershipBlock', $this->_membershipBlock);
365
366 if (!empty($this->_values['custom_pre_id'])) {
367 $preProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_pre_id']);
368 }
369
370 if (!empty($this->_values['custom_post_id'])) {
371 $postProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_post_id']);
372 }
373
374 if (((isset($postProfileType) && $postProfileType === 'Membership') ||
375 (isset($preProfileType) && $preProfileType === 'Membership')
376 ) &&
377 !$this->_membershipBlock['is_active']
378 ) {
379 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.'));
380 }
381
382 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock::getPledgeBlock($this->_id);
383
384 if ($pledgeBlock) {
385 $this->_values['pledge_block_id'] = $pledgeBlock['id'] ?? NULL;
386 $this->_values['max_reminders'] = $pledgeBlock['max_reminders'] ?? NULL;
387 $this->_values['initial_reminder_day'] = $pledgeBlock['initial_reminder_day'] ?? NULL;
388 $this->_values['additional_reminder_day'] = $pledgeBlock['additional_reminder_day'] ?? NULL;
389
390 //set pledge id in values
391 $pledgeId = CRM_Utils_Request::retrieve('pledgeId', 'Positive', $this);
392
393 //authenticate pledge user for pledge payment.
394 if ($pledgeId) {
395 $this->_values['pledge_id'] = $pledgeId;
396
397 //lets override w/ pledge campaign.
398 $this->_values['campaign_id'] = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge',
399 $pledgeId,
400 'campaign_id'
401 );
402 self::authenticatePledgeUser();
403 }
404 }
405 $this->set('values', $this->_values);
406 $this->set('fields', $this->_fields);
407 }
408
409 // Handle PCP
410 $pcpId = CRM_Utils_Request::retrieve('pcpId', 'Positive', $this);
411 if ($pcpId) {
412 $pcp = CRM_PCP_BAO_PCP::handlePcp($pcpId, 'contribute', $this->_values);
413 $this->_pcpId = $pcp['pcpId'];
414 $this->_pcpBlock = $pcp['pcpBlock'];
415 $this->_pcpInfo = $pcp['pcpInfo'];
416 }
417
418 // Link (button) for users to create their own Personal Campaign page
419 if ($linkText = CRM_PCP_BAO_PCP::getPcpBlockStatus($this->_id, 'contribute')) {
420 $linkTextUrl = CRM_Utils_System::url('civicrm/contribute/campaign',
421 "action=add&reset=1&pageId={$this->_id}&component=contribute",
422 FALSE, NULL, TRUE
423 );
424 $this->assign('linkTextUrl', $linkTextUrl);
425 $this->assign('linkText', $linkText);
426 }
427
428 //set pledge block if block id is set
429 if (!empty($this->_values['pledge_block_id'])) {
430 $this->assign('pledgeBlock', TRUE);
431 }
432
433 // check if one of the (amount , membership) blocks is active or not.
434 $this->_membershipBlock = $this->get('membershipBlock');
435
436 if (!$this->_values['amount_block_is_active'] &&
437 !$this->_membershipBlock['is_active'] &&
438 !$this->_priceSetId
439 ) {
440 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.'));
441 }
442
443 if ($this->_values['amount_block_is_active']) {
444 $this->set('amount_block_is_active', $this->_values['amount_block_is_active']);
445 }
446
447 $this->_contributeMode = $this->get('contributeMode');
448 $this->assign('contributeMode', $this->_contributeMode);
449
450 //assigning is_monetary and is_email_receipt to template
451 $this->assign('is_monetary', $this->_values['is_monetary']);
452 $this->assign('is_email_receipt', $this->_values['is_email_receipt']);
453 $this->assign('bltID', $this->_bltID);
454
455 //assign cancelSubscription URL to templates
456 $this->assign('cancelSubscriptionUrl',
457 CRM_Utils_Array::value('cancelSubscriptionUrl', $this->_values)
458 );
459
460 $title = !empty($this->_values['frontend_title']) ? $this->_values['frontend_title'] : $this->_values['title'];
461
462 $this->setTitle(($this->_pcpId ? $this->_pcpInfo['title'] : $title));
463 $this->_defaults = [];
464
465 $this->_amount = $this->get('amount');
466 // Assigning this to the template means it will be passed through to the payment form.
467 // This can, for example, by used by payment processors using client side encryption
468 $this->assign('currency', $this->getCurrency());
469
470 CRM_Contribute_BAO_Contribution_Utils::overrideDefaultCurrency($this->_values);
471
472 //lets allow user to override campaign.
473 $campID = CRM_Utils_Request::retrieve('campID', 'Positive', $this);
474 if ($campID && CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Campaign', $campID)) {
475 $this->_values['campaign_id'] = $campID;
476 }
477
478 //do check for cancel recurring and clean db, CRM-7696
479 if (CRM_Utils_Request::retrieve('cancel', 'Boolean')) {
480 self::cancelRecurring();
481 }
482
483 // check if billing block is required for pay later
484 if (!empty($this->_values['is_pay_later'])) {
485 $this->_isBillingAddressRequiredForPayLater = $this->_values['is_billing_required'] ?? NULL;
486 $this->assign('isBillingAddressRequiredForPayLater', $this->_isBillingAddressRequiredForPayLater);
487 }
488 }
489
490 /**
491 * Set the default values.
492 */
493 public function setDefaultValues() {
494 return $this->_defaults;
495 }
496
497 /**
498 * Assign the minimal set of variables to the template.
499 */
500 public function assignToTemplate() {
501 $this->set('name', $this->assignBillingName($this->_params));
502
503 $this->assign('paymentProcessor', $this->_paymentProcessor);
504 $vars = [
505 'amount',
506 'currencyID',
507 'credit_card_type',
508 'trxn_id',
509 'amount_level',
510 ];
511
512 $config = CRM_Core_Config::singleton();
513 if (isset($this->_values['is_recur']) && !empty($this->_paymentProcessor['is_recur'])) {
514 $this->assign('is_recur_enabled', 1);
515 $vars = array_merge($vars, [
516 'is_recur',
517 'frequency_interval',
518 'frequency_unit',
519 'installments',
520 ]);
521 }
522
523 if (in_array('CiviPledge', $config->enableComponents) &&
524 CRM_Utils_Array::value('is_pledge', $this->_params) == 1
525 ) {
526 $this->assign('pledge_enabled', 1);
527
528 $vars = array_merge($vars, [
529 'is_pledge',
530 'pledge_frequency_interval',
531 'pledge_frequency_unit',
532 'pledge_installments',
533 ]);
534 }
535
536 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
537 // function to get correct amount level consistently. Remove setting of the amount level in
538 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
539 // to cover all variants.
540 if (isset($this->_params['amount_other']) || isset($this->_params['selectMembership'])) {
541 $this->_params['amount_level'] = '';
542 }
543
544 foreach ($vars as $v) {
545 if (isset($this->_params[$v])) {
546 if ($v == "amount" && $this->_params[$v] === 0) {
547 $this->_params[$v] = CRM_Utils_Money::format($this->_params[$v], NULL, NULL, TRUE);
548 }
549 $this->assign($v, $this->_params[$v]);
550 }
551 }
552
553 $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
554 $this->_params,
555 $this->_bltID
556 ));
557
558 if (!empty($this->_params['onbehalf_profile_id']) && !empty($this->_params['onbehalf'])) {
559 $this->assign('onBehalfName', $this->_params['organization_name']);
560 $locTypeId = array_keys($this->_params['onbehalf_location']['email']);
561 $this->assign('onBehalfEmail', $this->_params['onbehalf_location']['email'][$locTypeId[0]]['email']);
562 }
563 $this->assignPaymentFields();
564 $this->assignEmailField();
565
566 // also assign the receipt_text
567 if (isset($this->_values['receipt_text'])) {
568 $this->assign('receipt_text', $this->_values['receipt_text']);
569 }
570 }
571
572 /**
573 * Assign email variable in the template.
574 */
575 public function assignEmailField() {
576 //If email exist in a profile, the default billing email field is not loaded on the page.
577 //Hence, assign the existing location type email by iterating through the params.
578 if ($this->_emailExists && empty($this->_params["email-{$this->_bltID}"])) {
579 foreach ($this->_params as $key => $val) {
580 if (substr($key, 0, 6) === 'email-') {
581 $this->assign('email', $this->_params[$key]);
582 break;
583 }
584 }
585 }
586 else {
587 $this->assign('email', CRM_Utils_Array::value("email-{$this->_bltID}", $this->_params));
588 }
589 }
590
591 /**
592 * Add the custom fields.
593 *
594 * @param int $id
595 * @param string $name
596 * @param bool $viewOnly
597 * @param null $profileContactType
598 * @param array $fieldTypes
599 */
600 public function buildCustom($id, $name, $viewOnly = FALSE, $profileContactType = NULL, $fieldTypes = NULL) {
601 if ($id) {
602 $contactID = $this->getContactID();
603
604 // we don't allow conflicting fields to be
605 // configured via profile - CRM 2100
606 $fieldsToIgnore = [
607 'receive_date' => 1,
608 'trxn_id' => 1,
609 'invoice_id' => 1,
610 'net_amount' => 1,
611 'fee_amount' => 1,
612 'non_deductible_amount' => 1,
613 'total_amount' => 1,
614 'amount_level' => 1,
615 'contribution_status_id' => 1,
616 // @todo replace payment_instrument with payment instrument id.
617 // both are available now but the id field is the most consistent.
618 'payment_instrument' => 1,
619 'payment_instrument_id' => 1,
620 'contribution_check_number' => 1,
621 'financial_type' => 1,
622 ];
623
624 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD, NULL, NULL, FALSE,
625 NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL
626 );
627
628 if ($fields) {
629 // determine if email exists in profile so we know if we need to manually insert CRM-2888, CRM-15067
630 foreach ($fields as $key => $field) {
631 if (substr($key, 0, 6) == 'email-' &&
632 !in_array($profileContactType, ['honor', 'onbehalf'])
633 ) {
634 $this->_emailExists = TRUE;
635 $this->set('emailExists', TRUE);
636 }
637 }
638
639 if (array_intersect_key($fields, $fieldsToIgnore)) {
640 $fields = array_diff_key($fields, $fieldsToIgnore);
641 CRM_Core_Session::setStatus(ts('Some of the profile fields cannot be configured for this page.'), ts('Warning'), 'alert');
642 }
643
644 //remove common fields only if profile is not configured for onbehalf/honor
645 if (!in_array($profileContactType, ['honor', 'onbehalf'])) {
646 $fields = array_diff_key($fields, $this->_fields);
647 }
648
649 CRM_Core_BAO_Address::checkContactSharedAddressFields($fields, $contactID);
650 $addCaptcha = FALSE;
651 // fetch file preview when not submitted yet, like in online contribution Confirm and ThankYou page
652 $viewOnlyFileValues = empty($profileContactType) ? [] : [$profileContactType => []];
653 foreach ($fields as $key => $field) {
654 if ($viewOnly &&
655 isset($field['data_type']) &&
656 $field['data_type'] == 'File' || ($viewOnly && $field['name'] == 'image_URL')
657 ) {
658 //retrieve file value from submitted values on basis of $profileContactType
659 $fileValue = $this->_params[$key] ?? NULL;
660 if (!empty($profileContactType) && !empty($this->_params[$profileContactType])) {
661 $fileValue = $this->_params[$profileContactType][$key] ?? NULL;
662 }
663
664 if ($fileValue) {
665 $path = $fileValue['name'] ?? NULL;
666 $fileType = $fileValue['type'] ?? NULL;
667 $fileValue = CRM_Utils_File::getFileURL($path, $fileType);
668 }
669
670 // format custom file value fetched from submitted value
671 if ($profileContactType) {
672 $viewOnlyFileValues[$profileContactType][$key] = $fileValue;
673 }
674 else {
675 $viewOnlyFileValues[$key] = $fileValue;
676 }
677
678 // On viewOnly use-case (as in online contribution Confirm page) we no longer need to set
679 // required property because being required file is already uploaded while registration
680 $field['is_required'] = FALSE;
681 }
682 if ($profileContactType) {
683 //Since we are showing honoree name separately so we are removing it from honoree profile just for display
684 if ($profileContactType == 'honor') {
685 $honoreeNamefields = [
686 'prefix_id',
687 'first_name',
688 'last_name',
689 'suffix_id',
690 'organization_name',
691 'household_name',
692 ];
693 if (in_array($field['name'], $honoreeNamefields)) {
694 unset($fields[$field['name']]);
695 continue;
696 }
697 }
698 if (!empty($fieldTypes) && in_array($field['field_type'], $fieldTypes)) {
699 CRM_Core_BAO_UFGroup::buildProfile(
700 $this,
701 $field,
702 CRM_Profile_Form::MODE_CREATE,
703 $contactID,
704 TRUE,
705 $profileContactType
706 );
707 $this->_fields[$profileContactType][$key] = $field;
708 }
709 else {
710 unset($fields[$key]);
711 }
712 }
713 else {
714 CRM_Core_BAO_UFGroup::buildProfile(
715 $this,
716 $field,
717 CRM_Profile_Form::MODE_CREATE,
718 $contactID,
719 TRUE
720 );
721 $this->_fields[$key] = $field;
722 }
723 // CRM-11316 Is ReCAPTCHA enabled for this profile AND is this an anonymous visitor
724 if ($field['add_captcha'] && !$this->_userID) {
725 $addCaptcha = TRUE;
726 }
727 }
728
729 $this->assign($name, $fields);
730
731 if ($profileContactType && count($viewOnlyFileValues[$profileContactType])) {
732 $this->assign('viewOnlyPrefixFileValues', $viewOnlyFileValues);
733 }
734 elseif (count($viewOnlyFileValues)) {
735 $this->assign('viewOnlyFileValues', $viewOnlyFileValues);
736 }
737
738 if ($addCaptcha && !$viewOnly) {
739 $this->enableCaptchaOnForm();
740 }
741 }
742 }
743 }
744
745 /**
746 * Enable ReCAPTCHA on Contribution form
747 */
748 protected function enableCaptchaOnForm() {
749 CRM_Utils_ReCAPTCHA::enableCaptchaOnForm($this);
750 }
751
752 /**
753 * Assign payment field information to the template.
754 *
755 * @throws \CRM_Core_Exception
756 * @throws \CiviCRM_API3_Exception
757 */
758 public function assignPaymentFields() {
759 //fix for CRM-3767
760 $isMonetary = FALSE;
761 if ($this->_amount > 0.0) {
762 $isMonetary = TRUE;
763 }
764 elseif (!empty($this->_params['selectMembership'])) {
765 $memFee = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params['selectMembership'], 'minimum_fee');
766 if ($memFee > 0.0) {
767 $isMonetary = TRUE;
768 }
769 }
770
771 // The concept of contributeMode is deprecated.
772 // The payment processor object can provide info about the fields it shows.
773 if ($isMonetary && is_a($this->_paymentProcessor['object'], 'CRM_Core_Payment')) {
774 /** @var \CRM_Core_Payment $paymentProcessorObject */
775 $paymentProcessorObject = $this->_paymentProcessor['object'];
776
777 $paymentFields = $paymentProcessorObject->getPaymentFormFields();
778 foreach ($paymentFields as $index => $paymentField) {
779 if (!isset($this->_params[$paymentField])) {
780 unset($paymentFields[$index]);
781 continue;
782 }
783 if ($paymentField === 'credit_card_exp_date') {
784 $date = CRM_Utils_Date::format(CRM_Utils_Array::value('credit_card_exp_date', $this->_params));
785 $date = CRM_Utils_Date::mysqlToIso($date);
786 $this->assign('credit_card_exp_date', $date);
787 }
788 elseif ($paymentField === 'credit_card_number') {
789 $this->assign('credit_card_number',
790 CRM_Utils_System::mungeCreditCard(CRM_Utils_Array::value('credit_card_number', $this->_params))
791 );
792 }
793 elseif ($paymentField === 'credit_card_type') {
794 $this->assign('credit_card_type', CRM_Core_PseudoConstant::getLabel(
795 'CRM_Core_BAO_FinancialTrxn',
796 'card_type_id',
797 CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $this->_params['credit_card_type'])
798 ));
799 }
800 else {
801 $this->assign($paymentField, $this->_params[$paymentField]);
802 }
803 }
804 $this->assign('paymentFieldsetLabel', CRM_Core_Payment_Form::getPaymentLabel($paymentProcessorObject));
805 $this->assign('paymentFields', $paymentFields);
806
807 }
808 }
809
810 /**
811 * Display ReCAPTCHA warning on Contribution form
812 */
813 protected function displayCaptchaWarning() {
814 if (CRM_Core_Permission::check("administer CiviCRM")) {
815 if (!CRM_Utils_ReCAPTCHA::hasSettingsAvailable()) {
816 $this->assign('displayCaptchaWarning', TRUE);
817 }
818 }
819 }
820
821 /**
822 * Check if ReCAPTCHA has to be added on Contribution form forcefully.
823 */
824 protected function hasToAddForcefully() {
825 return CRM_Utils_ReCAPTCHA::hasToAddForcefully();
826 }
827
828 /**
829 * Add onbehalf/honoree profile fields and native module fields.
830 *
831 * @param int $id
832 * @param CRM_Core_Form $form
833 *
834 * @throws \CRM_Core_Exception
835 */
836 public function buildComponentForm($id, $form) {
837 if (empty($id)) {
838 return;
839 }
840
841 $contactID = $this->getContactID();
842
843 foreach (['soft_credit', 'on_behalf'] as $module) {
844 if ($module === 'soft_credit') {
845 if (empty($form->_values['honoree_profile_id'])) {
846 continue;
847 }
848
849 if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $form->_values['honoree_profile_id'], 'is_active')) {
850 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.'));
851 }
852
853 $profileContactType = CRM_Core_BAO_UFGroup::getContactType($form->_values['honoree_profile_id']);
854 $requiredProfileFields = [
855 'Individual' => ['first_name', 'last_name'],
856 'Organization' => ['organization_name', 'email'],
857 'Household' => ['household_name', 'email'],
858 ];
859 $validProfile = CRM_Core_BAO_UFGroup::checkValidProfile($form->_values['honoree_profile_id'], $requiredProfileFields[$profileContactType]);
860 if (!$validProfile) {
861 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.'));
862 }
863
864 foreach (['honor_block_title', 'honor_block_text'] as $name) {
865 $form->assign($name, $form->_values[$name]);
866 }
867
868 $softCreditTypes = CRM_Core_OptionGroup::values("soft_credit_type", FALSE);
869
870 // radio button for Honor Type
871 foreach ($form->_values['soft_credit_types'] as $value) {
872 $honorTypes[$value] = $form->createElement('radio', NULL, NULL, $softCreditTypes[$value], $value);
873 }
874 $form->addGroup($honorTypes, 'soft_credit_type_id', NULL)->setAttribute('allowClear', TRUE);
875
876 $honoreeProfileFields = CRM_Core_BAO_UFGroup::getFields(
877 $this->_values['honoree_profile_id'], FALSE,
878 NULL, NULL,
879 NULL, FALSE,
880 NULL, TRUE,
881 NULL, CRM_Core_Permission::CREATE
882 );
883 $form->assign('honoreeProfileFields', $honoreeProfileFields);
884
885 // add the form elements
886 foreach ($honoreeProfileFields as $name => $field) {
887 // If soft credit type is not chosen then make omit requiredness from honoree profile fields
888 if (count($form->_submitValues) &&
889 empty($form->_submitValues['soft_credit_type_id']) &&
890 !empty($field['is_required'])
891 ) {
892 $field['is_required'] = FALSE;
893 }
894 CRM_Core_BAO_UFGroup::buildProfile($form, $field, CRM_Profile_Form::MODE_CREATE, NULL, FALSE, FALSE, NULL, 'honor');
895 }
896 }
897 else {
898 if (empty($form->_values['onbehalf_profile_id'])) {
899 continue;
900 }
901
902 if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $form->_values['onbehalf_profile_id'], 'is_active')) {
903 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.'));
904 }
905
906 $member = CRM_Member_BAO_Membership::getMembershipBlock($form->_id);
907 if (empty($member['is_active'])) {
908 $msg = ts('Mixed profile not allowed for on behalf of registration/sign up.');
909 $onBehalfProfile = CRM_Core_BAO_UFGroup::profileGroups($form->_values['onbehalf_profile_id']);
910 foreach (
911 [
912 'Individual',
913 'Organization',
914 'Household',
915 ] as $contactType
916 ) {
917 if (in_array($contactType, $onBehalfProfile) &&
918 (in_array('Membership', $onBehalfProfile) ||
919 in_array('Contribution', $onBehalfProfile)
920 )
921 ) {
922 CRM_Core_Error::statusBounce($msg);
923 }
924 }
925 }
926
927 if ($contactID) {
928 // retrieve all permissioned organizations of contact $contactID
929 $organizations = CRM_Contact_BAO_Relationship::getPermissionedContacts($contactID, NULL, NULL, 'Organization');
930
931 if (count($organizations)) {
932 // Related org url - pass checksum if needed
933 $args = [
934 'ufId' => $form->_values['onbehalf_profile_id'],
935 'cid' => '',
936 ];
937 if (!empty($_GET['cs'])) {
938 $args = [
939 'ufId' => $form->_values['onbehalf_profile_id'],
940 'uid' => $this->_contactID,
941 'cs' => $_GET['cs'],
942 'cid' => '',
943 ];
944 }
945 $locDataURL = CRM_Utils_System::url('civicrm/ajax/permlocation', $args, FALSE, NULL, FALSE);
946 $form->assign('locDataURL', $locDataURL);
947 }
948 if (count($organizations) > 0) {
949 $form->add('select', 'onbehalfof_id', '', CRM_Utils_Array::collect('name', $organizations));
950
951 $orgOptions = [
952 0 => ts('Select an existing organization'),
953 1 => ts('Enter a new organization'),
954 ];
955 $form->addRadio('org_option', ts('options'), $orgOptions);
956 $form->setDefaults(['org_option' => 0]);
957 }
958 }
959
960 $form->assign('fieldSetTitle', CRM_Core_BAO_UFGroup::getTitle($form->_values['onbehalf_profile_id']));
961
962 if (!empty($form->_values['is_for_organization'])) {
963 if ($form->_values['is_for_organization'] == 2) {
964 $form->assign('onBehalfRequired', TRUE);
965 }
966 else {
967 $form->addElement('checkbox', 'is_for_organization',
968 $form->_values['for_organization'],
969 NULL
970 );
971 }
972 }
973
974 $profileFields = CRM_Core_BAO_UFGroup::getFields(
975 $form->_values['onbehalf_profile_id'],
976 FALSE, CRM_Core_Action::VIEW, NULL,
977 NULL, FALSE, NULL, FALSE, NULL,
978 CRM_Core_Permission::CREATE, NULL
979 );
980
981 $form->assign('onBehalfOfFields', $profileFields);
982 if (!empty($form->_submitValues['onbehalf'])) {
983 if (!empty($form->_submitValues['onbehalfof_id'])) {
984 $form->assign('submittedOnBehalf', $form->_submitValues['onbehalfof_id']);
985 }
986 $form->assign('submittedOnBehalfInfo', json_encode(str_replace('"', '\"', $form->_submitValues['onbehalf']), JSON_HEX_APOS));
987 }
988
989 $fieldTypes = ['Contact', 'Organization'];
990 if (!empty($form->_membershipBlock)) {
991 $fieldTypes = array_merge($fieldTypes, ['Membership']);
992 }
993 $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization');
994 $fieldTypes = array_merge($fieldTypes, $contactSubType);
995
996 foreach ($profileFields as $name => $field) {
997 if (in_array($field['field_type'], $fieldTypes)) {
998 list($prefixName, $index) = CRM_Utils_System::explode('-', $name, 2);
999 if (in_array($prefixName, ['organization_name', 'email']) && empty($field['is_required'])) {
1000 $field['is_required'] = 1;
1001 }
1002 if (count($form->_submitValues) &&
1003 empty($form->_submitValues['is_for_organization']) &&
1004 $form->_values['is_for_organization'] == 1 &&
1005 !empty($field['is_required'])
1006 ) {
1007 $field['is_required'] = FALSE;
1008 }
1009 CRM_Core_BAO_UFGroup::buildProfile($form, $field, NULL, NULL, FALSE, 'onbehalf', NULL, 'onbehalf');
1010 }
1011 }
1012 }
1013 }
1014
1015 }
1016
1017 /**
1018 * Check template file exists.
1019 *
1020 * @param string $suffix
1021 *
1022 * @return null|string
1023 */
1024 public function checkTemplateFileExists($suffix = NULL) {
1025 if ($this->_id) {
1026 $templateFile = "CRM/Contribute/Form/Contribution/{$this->_id}/{$this->_name}.{$suffix}tpl";
1027 $template = CRM_Core_Form::getTemplate();
1028 if ($template->template_exists($templateFile)) {
1029 return $templateFile;
1030 }
1031 }
1032 return NULL;
1033 }
1034
1035 /**
1036 * Use the form name to create the tpl file name.
1037 *
1038 * @return string
1039 */
1040 public function getTemplateFileName() {
1041 $fileName = $this->checkTemplateFileExists();
1042 return $fileName ?: parent::getTemplateFileName();
1043 }
1044
1045 /**
1046 * Add the extra.tpl in.
1047 *
1048 * Default extra tpl file basically just replaces .tpl with .extra.tpl
1049 * i.e. we do not override - why isn't this done at the CRM_Core_Form level?
1050 *
1051 * @return string
1052 */
1053 public function overrideExtraTemplateFileName() {
1054 $fileName = $this->checkTemplateFileExists('extra.');
1055 return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
1056 }
1057
1058 /**
1059 * Authenticate pledge user during online payment.
1060 *
1061 * @throws \CRM_Core_Exception
1062 */
1063 public function authenticatePledgeUser() {
1064 //get the userChecksum and contact id
1065 $userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this);
1066 $contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
1067
1068 //get pledge status and contact id
1069 $pledgeValues = [];
1070 $pledgeParams = ['id' => $this->_values['pledge_id']];
1071 $returnProperties = ['contact_id', 'status_id'];
1072 CRM_Core_DAO::commonRetrieve('CRM_Pledge_DAO_Pledge', $pledgeParams, $pledgeValues, $returnProperties);
1073
1074 //get all status
1075 $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1076 $validStatus = [
1077 array_search('Pending', $allStatus),
1078 array_search('In Progress', $allStatus),
1079 array_search('Overdue', $allStatus),
1080 ];
1081
1082 $validUser = FALSE;
1083 if ($this->_userID &&
1084 $this->_userID == $pledgeValues['contact_id']
1085 ) {
1086 //check for authenticated user.
1087 $validUser = TRUE;
1088 }
1089 elseif ($userChecksum && $pledgeValues['contact_id']) {
1090 //check for anonymous user.
1091 $validUser = CRM_Contact_BAO_Contact_Utils::validChecksum($pledgeValues['contact_id'], $userChecksum);
1092
1093 //make sure cid is same as pledge contact id
1094 if ($validUser && ($pledgeValues['contact_id'] != $contactID)) {
1095 $validUser = FALSE;
1096 }
1097 }
1098
1099 if (!$validUser) {
1100 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."));
1101 }
1102
1103 //check for valid pledge status.
1104 if (!in_array($pledgeValues['status_id'], $validStatus)) {
1105 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)]));
1106 }
1107 }
1108
1109 /**
1110 * Cancel recurring contributions.
1111 *
1112 * In case user cancel recurring contribution,
1113 * When we get the control back from payment gate way
1114 * lets delete the recurring and related contribution.
1115 *
1116 * @throws \CRM_Core_Exception
1117 */
1118 public function cancelRecurring() {
1119 $isCancel = CRM_Utils_Request::retrieve('cancel', 'Boolean');
1120 if ($isCancel) {
1121 $isRecur = CRM_Utils_Request::retrieve('isRecur', 'Boolean');
1122 $recurId = CRM_Utils_Request::retrieve('recurId', 'Positive');
1123 //clean db for recurring contribution.
1124 if ($isRecur && $recurId) {
1125 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($recurId);
1126 }
1127 $contribId = CRM_Utils_Request::retrieve('contribId', 'Positive');
1128 if ($contribId) {
1129 CRM_Contribute_BAO_Contribution::deleteContribution($contribId);
1130 }
1131 }
1132 }
1133
1134 /**
1135 * Build Membership Block in Contribution Pages.
1136 *
1137 * @param int $cid
1138 * Contact checked for having a current membership for a particular membership.
1139 * @param bool $isContributionMainPage
1140 * Is this the main page? If so add form input fields.
1141 * (or better yet don't have this functionality in a function shared with forms that don't share it).
1142 * @param int|array $selectedMembershipTypeID
1143 * Selected membership id.
1144 * @param bool $thankPage
1145 * Thank you page.
1146 * @param null $isTest
1147 *
1148 * @return bool
1149 * Is this a separate membership payment
1150 *
1151 * @throws \CiviCRM_API3_Exception
1152 * @throws \CRM_Core_Exception
1153 */
1154 protected function buildMembershipBlock(
1155 $cid,
1156 $isContributionMainPage = FALSE,
1157 $selectedMembershipTypeID = NULL,
1158 $thankPage = FALSE,
1159 $isTest = NULL
1160 ) {
1161
1162 $separateMembershipPayment = FALSE;
1163 if ($this->_membershipBlock) {
1164 $this->_currentMemberships = [];
1165
1166 $membershipTypeIds = $membershipTypes = $radio = [];
1167 $membershipPriceset = (!empty($this->_priceSetId) && $this->_useForMember);
1168
1169 $allowAutoRenewMembership = $autoRenewOption = FALSE;
1170 $autoRenewMembershipTypeOptions = [];
1171
1172 $separateMembershipPayment = $this->_membershipBlock['is_separate_payment'] ?? NULL;
1173
1174 if ($membershipPriceset) {
1175 foreach ($this->_priceSet['fields'] as $pField) {
1176 if (empty($pField['options'])) {
1177 continue;
1178 }
1179 foreach ($pField['options'] as $opId => $opValues) {
1180 if (empty($opValues['membership_type_id'])) {
1181 continue;
1182 }
1183 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
1184 }
1185 }
1186 }
1187 elseif (!empty($this->_membershipBlock['membership_types'])) {
1188 $membershipTypeIds = explode(',', $this->_membershipBlock['membership_types']);
1189 }
1190
1191 if (!empty($membershipTypeIds)) {
1192 //set status message if wrong membershipType is included in membershipBlock
1193 if (isset($this->_mid) && !$membershipPriceset) {
1194 $membershipTypeID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
1195 $this->_mid,
1196 'membership_type_id'
1197 );
1198 if (!in_array($membershipTypeID, $membershipTypeIds)) {
1199 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');
1200 }
1201 }
1202
1203 $membershipTypeValues = CRM_Member_BAO_Membership::buildMembershipTypeValues($this, $membershipTypeIds);
1204 $this->_membershipTypeValues = $membershipTypeValues;
1205 $endDate = NULL;
1206
1207 // Check if we support auto-renew on this contribution page
1208 // FIXME: If any of the payment processors do NOT support recurring you cannot setup an
1209 // auto-renew payment even if that processor is not selected.
1210 $allowAutoRenewOpt = TRUE;
1211 if (is_array($this->_paymentProcessors)) {
1212 foreach ($this->_paymentProcessors as $id => $val) {
1213 if ($id && !$val['is_recur']) {
1214 $allowAutoRenewOpt = FALSE;
1215 }
1216 }
1217 }
1218 foreach ($membershipTypeIds as $value) {
1219 $memType = $membershipTypeValues[$value];
1220 if ($selectedMembershipTypeID != NULL) {
1221 if ($memType['id'] == $selectedMembershipTypeID) {
1222 $this->assign('minimum_fee',
1223 CRM_Utils_Array::value('minimum_fee', $memType)
1224 );
1225 $this->assign('membership_name', $memType['name']);
1226 if (!$thankPage && $cid) {
1227 $membership = new CRM_Member_DAO_Membership();
1228 $membership->contact_id = $cid;
1229 $membership->membership_type_id = $memType['id'];
1230 if ($membership->find(TRUE)) {
1231 $this->assign('renewal_mode', TRUE);
1232 $memType['current_membership'] = $membership->end_date;
1233 $this->_currentMemberships[$membership->membership_type_id] = $membership->membership_type_id;
1234 }
1235 }
1236 $membershipTypes[] = $memType;
1237 }
1238 }
1239 elseif ($memType['is_active']) {
1240
1241 if ($allowAutoRenewOpt) {
1242 $javascriptMethod = ['onclick' => "return showHideAutoRenew( this.value );"];
1243 $isAvailableAutoRenew = $this->_membershipBlock['auto_renew'][$value] ?? 1;
1244 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int) $memType['auto_renew'] * $isAvailableAutoRenew;
1245 $allowAutoRenewMembership = TRUE;
1246 }
1247 else {
1248 $javascriptMethod = NULL;
1249 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = 0;
1250 }
1251
1252 //add membership type.
1253 $radio[$memType['id']] = $this->createElement('radio', NULL, NULL, NULL,
1254 $memType['id'], $javascriptMethod
1255 );
1256 if ($cid) {
1257 $membership = new CRM_Member_DAO_Membership();
1258 $membership->contact_id = $cid;
1259 $membership->membership_type_id = $memType['id'];
1260
1261 //show current membership, skip pending and cancelled membership records,
1262 //because we take first membership record id for renewal
1263 $membership->whereAdd('status_id != 5 AND status_id !=6');
1264
1265 if (!is_null($isTest)) {
1266 $membership->is_test = $isTest;
1267 }
1268
1269 //CRM-4297
1270 $membership->orderBy('end_date DESC');
1271
1272 if ($membership->find(TRUE)) {
1273 if (!$membership->end_date) {
1274 unset($radio[$memType['id']]);
1275 $this->assign('islifetime', TRUE);
1276 continue;
1277 }
1278 $this->assign('renewal_mode', TRUE);
1279 $this->_currentMemberships[$membership->membership_type_id] = $membership->membership_type_id;
1280 $memType['current_membership'] = $membership->end_date;
1281 if (!$endDate) {
1282 $endDate = $memType['current_membership'];
1283 $this->_defaultMemTypeId = $memType['id'];
1284 }
1285 if ($memType['current_membership'] < $endDate) {
1286 $endDate = $memType['current_membership'];
1287 $this->_defaultMemTypeId = $memType['id'];
1288 }
1289 }
1290 }
1291 $membershipTypes[] = $memType;
1292 }
1293 }
1294 }
1295
1296 $this->assign('membershipBlock', $this->_membershipBlock);
1297 $this->assign('showRadio', $isContributionMainPage);
1298 $this->assign('membershipTypes', $membershipTypes);
1299 $this->assign('allowAutoRenewMembership', $allowAutoRenewMembership);
1300 $this->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
1301 //give preference to user submitted auto_renew value.
1302 $takeUserSubmittedAutoRenew = (!empty($_POST) || $this->isSubmitted());
1303 $this->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
1304
1305 // Assign autorenew option (0:hide,1:optional,2:required) so we can use it in confirmation etc.
1306 $autoRenewOption = CRM_Price_BAO_PriceSet::checkAutoRenewForPriceSet($this->_priceSetId);
1307 //$selectedMembershipTypeID is retrieved as an array for membership priceset if multiple
1308 //options for different organisation is selected on the contribution page.
1309 if (is_numeric($selectedMembershipTypeID) && isset($membershipTypeValues[$selectedMembershipTypeID]['auto_renew'])) {
1310 $this->assign('autoRenewOption', $membershipTypeValues[$selectedMembershipTypeID]['auto_renew']);
1311 }
1312 else {
1313 $this->assign('autoRenewOption', $autoRenewOption);
1314 }
1315
1316 if ($isContributionMainPage) {
1317 if (!$membershipPriceset) {
1318 if (!$this->_membershipBlock['is_required']) {
1319 $this->assign('showRadioNoThanks', TRUE);
1320 $radio[''] = $this->createElement('radio', NULL, NULL, NULL, 'no_thanks', NULL);
1321 $this->addGroup($radio, 'selectMembership', NULL);
1322 }
1323 elseif ($this->_membershipBlock['is_required'] && count($radio) == 1) {
1324 $temp = array_keys($radio);
1325 $this->add('hidden', 'selectMembership', $temp[0], ['id' => 'selectMembership']);
1326 $this->assign('singleMembership', TRUE);
1327 $this->assign('showRadio', FALSE);
1328 }
1329 else {
1330 $this->addGroup($radio, 'selectMembership', NULL);
1331 }
1332
1333 $this->addRule('selectMembership', ts('Please select one of the memberships.'), 'required');
1334 }
1335
1336 if ((!$this->_values['is_pay_later'] || is_array($this->_paymentProcessors)) && ($allowAutoRenewMembership || $autoRenewOption)) {
1337 if ($autoRenewOption == 2) {
1338 $this->addElement('hidden', 'auto_renew', ts('Please renew my membership automatically.'));
1339 }
1340 else {
1341 $this->addElement('checkbox', 'auto_renew', ts('Please renew my membership automatically.'));
1342 }
1343 }
1344
1345 }
1346 }
1347
1348 return $separateMembershipPayment;
1349 }
1350
1351 /**
1352 * Determine if recurring parameters need to be added to the form parameters.
1353 *
1354 * - is_recur
1355 * - frequency_interval
1356 * - frequency_unit
1357 *
1358 * For membership this is based on the membership type.
1359 *
1360 * This needs to be done before processing the pre-approval redirect where relevant on the main page or before any payment processing.
1361 *
1362 * Arguably the form should start to build $this->_params in the pre-process main page & use that array consistently throughout.
1363 */
1364 protected function setRecurringMembershipParams() {
1365 $selectedMembershipTypeID = $this->_params['selectMembership'] ?? NULL;
1366 if ($selectedMembershipTypeID) {
1367 // @todo the price_x fields will ALWAYS allow us to determine the membership - so we should ignore
1368 // 'selectMembership' and calculate from the price_x fields so we have one method that always works
1369 // this is lazy & only catches when selectMembership is set, but the worst of all worlds would be to fix
1370 // this with an else (calculate for price set).
1371 $membershipTypes = CRM_Price_BAO_PriceSet::getMembershipTypesFromPriceSet($this->_priceSetId);
1372 if (in_array($selectedMembershipTypeID, $membershipTypes['autorenew_required'])
1373 || (in_array($selectedMembershipTypeID, $membershipTypes['autorenew_optional']) &&
1374 !empty($this->_params['is_recur']))
1375 ) {
1376 $this->_params['auto_renew'] = TRUE;
1377 }
1378 }
1379 if ((!empty($this->_params['selectMembership']) || !empty($this->_params['priceSetId']))
1380 && !empty($this->_paymentProcessor['is_recur']) &&
1381 !empty($this->_params['auto_renew'])
1382 && empty($this->_params['is_recur']) && empty($this->_params['frequency_interval'])
1383 ) {
1384
1385 $this->_params['is_recur'] = $this->_values['is_recur'] = 1;
1386 // check if price set is not quick config
1387 if (!empty($this->_params['priceSetId']) && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params['priceSetId'], 'is_quick_config')) {
1388 list($this->_params['frequency_interval'], $this->_params['frequency_unit']) = CRM_Price_BAO_PriceSet::getRecurDetails($this->_params['priceSetId']);
1389 }
1390 else {
1391 // FIXME: set interval and unit based on selected membership type
1392 $this->_params['frequency_interval'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
1393 $this->_params['selectMembership'], 'duration_interval'
1394 );
1395 $this->_params['frequency_unit'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType',
1396 $this->_params['selectMembership'], 'duration_unit'
1397 );
1398 }
1399 }
1400 }
1401
1402 /**
1403 * Get the payment processor object for the submission, returning the manual one for offline payments.
1404 *
1405 * @return CRM_Core_Payment
1406 */
1407 protected function getPaymentProcessorObject() {
1408 if (!empty($this->_paymentProcessor)) {
1409 return $this->_paymentProcessor['object'];
1410 }
1411 return new CRM_Core_Payment_Manual();
1412 }
1413
1414 /**
1415 * Get the amount for the main contribution.
1416 *
1417 * The goal is to expand this function so that all the argy-bargy of figuring out the amount
1418 * winds up here as the main spaghetti shrinks.
1419 *
1420 * If there is a separate membership contribution this is the 'other one'. Otherwise there
1421 * is only one.
1422 *
1423 * @param $params
1424 *
1425 * @return float
1426 *
1427 * @throws \CiviCRM_API3_Exception
1428 */
1429 protected function getMainContributionAmount($params) {
1430 if (!empty($params['selectMembership'])) {
1431 if (empty($params['amount']) && !$this->_separateMembershipPayment) {
1432 return CRM_Member_BAO_MembershipType::getMembershipType($params['selectMembership'])['minimum_fee'] ?? 0;
1433 }
1434 }
1435 return $params['amount'] ?? 0;
1436 }
1437
1438 /**
1439 * Wrapper for processAmount that also sets autorenew.
1440 *
1441 * @param $fields
1442 * This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
1443 * And, it would make sense to introduce caching into that function and call it from here rather than
1444 * require the $fields array which is passed from pillar to post around the form in order to pass it in here.
1445 * @param array $params
1446 * Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
1447 * @param $lineItems
1448 * Line item array to be altered.
1449 * @param int $priceSetID
1450 */
1451 public function processAmountAndGetAutoRenew($fields, &$params, &$lineItems, $priceSetID = NULL) {
1452 CRM_Price_BAO_PriceSet::processAmount($fields, $params, $lineItems, $priceSetID);
1453 $autoRenew = [];
1454 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
1455 foreach ($lineItems as $lineItem) {
1456 if (!empty($lineItem['auto_renew']) &&
1457 is_numeric($lineItem['auto_renew'])
1458 ) {
1459 $autoRenew[$lineItem['auto_renew']] += $lineItem['line_total'];
1460 }
1461 }
1462 if (count($autoRenew) > 1) {
1463 $params['autoRenew'] = $autoRenew;
1464 }
1465 }
1466
1467 }