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