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