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