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