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