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