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