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