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