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