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