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