Merge pull request #15421 from artfulrobot/queue-safety
[civicrm-core.git] / CRM / Contribute / Form / Contribution / Main.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
32 */
33
34 /**
35 * This class generates form components for processing a Contribution.
36 */
37 class CRM_Contribute_Form_Contribution_Main extends CRM_Contribute_Form_ContributionBase {
38
39 /**
40 * Define default MembershipType Id.
41 * @var int
42 */
43 public $_defaultMemTypeId;
44
45 public $_paymentProcessors;
46
47 public $_membershipTypeValues;
48
49 public $_useForMember;
50
51 /**
52 * Array of payment related fields to potentially display on this form (generally credit card or debit card fields). This is rendered via billingBlock.tpl
53 * @var array
54 */
55 public $_paymentFields = [];
56
57 protected $_paymentProcessorID;
58 protected $_snippet;
59
60 /**
61 * Set variables up before form is built.
62 */
63 public function preProcess() {
64 parent::preProcess();
65
66 $this->_paymentProcessors = $this->get('paymentProcessors');
67 $this->preProcessPaymentOptions();
68
69 $this->assignFormVariablesByContributionID();
70
71 // Make the contributionPageID available to the template
72 $this->assign('contributionPageID', $this->_id);
73 $this->assign('ccid', $this->_ccid);
74 $this->assign('isShare', CRM_Utils_Array::value('is_share', $this->_values));
75 $this->assign('isConfirmEnabled', CRM_Utils_Array::value('is_confirm_enabled', $this->_values));
76
77 $this->assign('reset', CRM_Utils_Request::retrieve('reset', 'Boolean'));
78 $this->assign('mainDisplay', CRM_Utils_Request::retrieve('_qf_Main_display', 'Boolean',
79 CRM_Core_DAO::$_nullObject));
80
81 if (!empty($this->_pcpInfo['id']) && !empty($this->_pcpInfo['intro_text'])) {
82 $this->assign('intro_text', $this->_pcpInfo['intro_text']);
83 }
84 elseif (!empty($this->_values['intro_text'])) {
85 $this->assign('intro_text', $this->_values['intro_text']);
86 }
87
88 $qParams = "reset=1&amp;id={$this->_id}";
89 if ($pcpId = CRM_Utils_Array::value('pcp_id', $this->_pcpInfo)) {
90 $qParams .= "&amp;pcpId={$pcpId}";
91 }
92 $this->assign('qParams', $qParams);
93
94 if (!empty($this->_values['footer_text'])) {
95 $this->assign('footer_text', $this->_values['footer_text']);
96 }
97 }
98
99 /**
100 * Set the default values.
101 */
102 public function setDefaultValues() {
103 // check if the user is registered and we have a contact ID
104 $contactID = $this->getContactID();
105
106 if (!empty($contactID)) {
107 $fields = [];
108 $removeCustomFieldTypes = ['Contribution', 'Membership'];
109 $contribFields = CRM_Contribute_BAO_Contribution::getContributionFields();
110
111 // remove component related fields
112 foreach ($this->_fields as $name => $dontCare) {
113 //don't set custom data Used for Contribution (CRM-1344)
114 if (substr($name, 0, 7) == 'custom_') {
115 $id = substr($name, 7);
116 if (!CRM_Core_BAO_CustomGroup::checkCustomField($id, $removeCustomFieldTypes)) {
117 continue;
118 }
119 // ignore component fields
120 }
121 elseif (array_key_exists($name, $contribFields) || (substr($name, 0, 11) == 'membership_') || (substr($name, 0, 13) == 'contribution_')) {
122 continue;
123 }
124 $fields[$name] = 1;
125 }
126
127 if (!empty($fields)) {
128 CRM_Core_BAO_UFGroup::setProfileDefaults($contactID, $fields, $this->_defaults);
129 }
130
131 $billingDefaults = $this->getProfileDefaults('Billing', $contactID);
132 $this->_defaults = array_merge($this->_defaults, $billingDefaults);
133 }
134 if (!empty($this->_ccid) && !empty($this->_pendingAmount)) {
135 $this->_defaults['total_amount'] = CRM_Utils_Money::format($this->_pendingAmount, NULL, '%a');
136 }
137
138 /*
139 * hack to simplify credit card entry for testing
140 *
141 * $this->_defaults['credit_card_type'] = 'Visa';
142 * $this->_defaults['amount'] = 168;
143 * $this->_defaults['credit_card_number'] = '4111111111111111';
144 * $this->_defaults['cvv2'] = '000';
145 * $this->_defaults['credit_card_exp_date'] = array('Y' => date('Y')+1, 'M' => '05');
146 * // hack to simplify direct debit entry for testing
147 * $this->_defaults['account_holder'] = 'Max Müller';
148 * $this->_defaults['bank_account_number'] = '12345678';
149 * $this->_defaults['bank_identification_number'] = '12030000';
150 * $this->_defaults['bank_name'] = 'Bankname';
151 */
152
153 //build set default for pledge overdue payment.
154 if (!empty($this->_values['pledge_id'])) {
155 //used to record completed pledge payment ids used later for honor default
156 $completedContributionIds = [];
157 $pledgePayments = CRM_Pledge_BAO_PledgePayment::getPledgePayments($this->_values['pledge_id']);
158
159 $paymentAmount = 0;
160 $duePayment = FALSE;
161 foreach ($pledgePayments as $payId => $value) {
162 if ($value['status'] == 'Overdue') {
163 $this->_defaults['pledge_amount'][$payId] = 1;
164 $paymentAmount += $value['scheduled_amount'];
165 }
166 elseif (!$duePayment && $value['status'] == 'Pending') {
167 $this->_defaults['pledge_amount'][$payId] = 1;
168 $paymentAmount += $value['scheduled_amount'];
169 $duePayment = TRUE;
170 }
171 elseif ($value['status'] == 'Completed' && $value['contribution_id']) {
172 $completedContributionIds[] = $value['contribution_id'];
173 }
174 }
175 $this->_defaults['price_' . $this->_priceSetId] = $paymentAmount;
176
177 if (count($completedContributionIds)) {
178 $softCredit = [];
179 foreach ($completedContributionIds as $id) {
180 $softCredit = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($id);
181 }
182 if (isset($softCredit['soft_credit'])) {
183 $this->_defaults['soft_credit_type_id'] = $softCredit['soft_credit'][1]['soft_credit_type'];
184
185 //since honoree profile fieldname of fields are prefixed with 'honor'
186 //we need to reformat the fieldname to append prefix during setting default values
187 CRM_Core_BAO_UFGroup::setProfileDefaults(
188 $softCredit['soft_credit'][1]['contact_id'],
189 CRM_Core_BAO_UFGroup::getFields($this->_honoreeProfileId),
190 $defaults
191 );
192 foreach ($defaults as $fieldName => $value) {
193 $this->_defaults['honor[' . $fieldName . ']'] = $value;
194 }
195 }
196 }
197 }
198 elseif (!empty($this->_values['pledge_block_id'])) {
199 //set default to one time contribution.
200 $this->_defaults['is_pledge'] = 0;
201 }
202
203 // to process Custom data that are appended to URL
204 $getDefaults = CRM_Core_BAO_CustomGroup::extractGetParams($this, "'Contact', 'Individual', 'Contribution'");
205 $this->_defaults = array_merge($this->_defaults, $getDefaults);
206
207 $config = CRM_Core_Config::singleton();
208 // set default country from config if no country set
209 if (empty($this->_defaults["billing_country_id-{$this->_bltID}"])) {
210 $this->_defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
211 }
212
213 // set default state/province from config if no state/province set
214 if (empty($this->_defaults["billing_state_province_id-{$this->_bltID}"])) {
215 $this->_defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
216 }
217
218 $entityId = $memtypeID = NULL;
219 if ($this->_priceSetId) {
220 if (($this->_useForMember && !empty($this->_currentMemberships)) || $this->_defaultMemTypeId) {
221 $selectedCurrentMemTypes = [];
222 foreach ($this->_priceSet['fields'] as $key => $val) {
223 foreach ($val['options'] as $keys => $values) {
224 $opMemTypeId = CRM_Utils_Array::value('membership_type_id', $values);
225 $priceFieldName = 'price_' . $values['price_field_id'];
226 $priceFieldValue = CRM_Price_BAO_PriceSet::getPriceFieldValueFromURL($this, $priceFieldName);
227 if (!empty($priceFieldValue)) {
228 CRM_Price_BAO_PriceSet::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $this->_defaults);
229 // break here to prevent overwriting of default due to 'is_default'
230 // option configuration or setting of current membership or
231 // membership for related organization.
232 // The value sent via URL get's higher priority.
233 break;
234 }
235 elseif ($opMemTypeId &&
236 in_array($opMemTypeId, $this->_currentMemberships) &&
237 !in_array($opMemTypeId, $selectedCurrentMemTypes)
238 ) {
239 CRM_Price_BAO_PriceSet::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $this->_defaults);
240 $memtypeID = $selectedCurrentMemTypes[] = $values['membership_type_id'];
241 }
242 elseif (!empty($values['is_default']) && !$opMemTypeId && (!isset($this->_defaults[$priceFieldName]) ||
243 ($val['html_type'] == 'CheckBox' && !isset($this->_defaults[$priceFieldName][$keys])))) {
244 CRM_Price_BAO_PriceSet::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $this->_defaults);
245 $memtypeID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $this->_defaults[$priceFieldName], 'membership_type_id');
246 }
247 }
248 }
249 $entityId = CRM_Utils_Array::value('id', CRM_Member_BAO_Membership::getContactMembership($contactID, $memtypeID, NULL));
250 }
251 else {
252 CRM_Price_BAO_PriceSet::setDefaultPriceSet($this, $this->_defaults);
253 }
254 }
255
256 //set custom field defaults set by admin if value is not set
257 if (!empty($this->_fields)) {
258 //load default campaign from page.
259 if (array_key_exists('contribution_campaign_id', $this->_fields)) {
260 $this->_defaults['contribution_campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values);
261 }
262
263 //set custom field defaults
264 foreach ($this->_fields as $name => $field) {
265 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
266 if (!isset($this->_defaults[$name])) {
267 CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $this->_defaults,
268 $entityId, CRM_Profile_Form::MODE_REGISTER
269 );
270 }
271 }
272 }
273 }
274
275 if (!empty($this->_paymentProcessors)) {
276 foreach ($this->_paymentProcessors as $pid => $value) {
277 if (!empty($value['is_default'])) {
278 $this->_defaults['payment_processor_id'] = $pid;
279 }
280 }
281 }
282
283 return $this->_defaults;
284 }
285
286 /**
287 * Build the form object.
288 */
289 public function buildQuickForm() {
290 // build profiles first so that we can determine address fields etc
291 // and then show copy address checkbox
292 if (empty($this->_ccid)) {
293 $this->buildCustom($this->_values['custom_pre_id'], 'customPre');
294 $this->buildCustom($this->_values['custom_post_id'], 'customPost');
295
296 // CRM-18399: used by template to pass pre profile id as a url arg
297 $this->assign('custom_pre_id', $this->_values['custom_pre_id']);
298
299 $this->buildComponentForm($this->_id, $this);
300 }
301
302 if (count($this->_paymentProcessors) >= 1 && !isset($this->_paymentProcessors[0]) && !$this->get_template_vars("isCaptcha") && $this->hasToAddForcefully()) {
303 if (!$this->_userID) {
304 $this->enableCaptchaOnForm();
305 }
306 else {
307 $this->displayCaptchaWarning();
308 }
309 }
310
311 // Build payment processor form
312 CRM_Core_Payment_ProcessorForm::buildQuickForm($this);
313
314 $config = CRM_Core_Config::singleton();
315
316 $contactID = $this->getContactID();
317 if ($contactID) {
318 $this->assign('contact_id', $contactID);
319 $this->assign('display_name', CRM_Contact_BAO_Contact::displayName($contactID));
320 }
321
322 $this->applyFilter('__ALL__', 'trim');
323 if (empty($this->_ccid)) {
324 if ($this->_emailExists == FALSE) {
325 $this->add('text', "email-{$this->_bltID}",
326 ts('Email Address'),
327 ['size' => 30, 'maxlength' => 60, 'class' => 'email'],
328 TRUE
329 );
330 $this->assign('showMainEmail', TRUE);
331 $this->addRule("email-{$this->_bltID}", ts('Email is not valid.'), 'email');
332 }
333 }
334 else {
335 $this->addElement('hidden', "email-{$this->_bltID}", 1);
336 $this->add('text', 'total_amount', ts('Total Amount'), ['readonly' => TRUE], FALSE);
337 }
338 $pps = [];
339 //@todo - this should be replaced by a check as to whether billing fields are set
340 $onlinePaymentProcessorEnabled = FALSE;
341 if (!empty($this->_paymentProcessors)) {
342 foreach ($this->_paymentProcessors as $key => $name) {
343 if ($name['billing_mode'] == 1) {
344 $onlinePaymentProcessorEnabled = TRUE;
345 }
346 $pps[$key] = $name['name'];
347 }
348 }
349 if (!empty($this->_values['is_pay_later'])) {
350 $pps[0] = $this->_values['pay_later_text'];
351 }
352
353 if (count($pps) > 1) {
354 $this->addRadio('payment_processor_id', ts('Payment Method'), $pps,
355 NULL, "&nbsp;"
356 );
357 }
358 elseif (!empty($pps)) {
359 $key = array_keys($pps);
360 $key = array_pop($key);
361 $this->addElement('hidden', 'payment_processor_id', $key);
362 if ($key === 0) {
363 $this->assign('is_pay_later', $this->_values['is_pay_later']);
364 $this->assign('pay_later_text', $this->_values['pay_later_text']);
365 }
366 }
367
368 $contactID = $this->getContactID();
369 if ($this->getContactID() === 0) {
370 $this->addCidZeroOptions($onlinePaymentProcessorEnabled);
371 }
372
373 //build pledge block.
374 $this->_useForMember = 0;
375 //don't build membership block when pledge_id is passed
376 if (empty($this->_values['pledge_id']) && empty($this->_ccid)) {
377 $this->_separateMembershipPayment = FALSE;
378 if (in_array('CiviMember', $config->enableComponents)) {
379 $isTest = 0;
380 if ($this->_action & CRM_Core_Action::PREVIEW) {
381 $isTest = 1;
382 }
383
384 if ($this->_priceSetId &&
385 (CRM_Core_Component::getComponentID('CiviMember') == CRM_Utils_Array::value('extends', $this->_priceSet))
386 ) {
387 $this->_useForMember = 1;
388 $this->set('useForMember', $this->_useForMember);
389 }
390
391 $this->_separateMembershipPayment = $this->buildMembershipBlock(
392 $this->_membershipContactID,
393 TRUE, NULL, FALSE,
394 $isTest
395 );
396 }
397 $this->set('separateMembershipPayment', $this->_separateMembershipPayment);
398 }
399 $this->assign('useForMember', $this->_useForMember);
400 // If we configured price set for contribution page
401 // we are not allow membership signup as well as any
402 // other contribution amount field, CRM-5095
403 if (isset($this->_priceSetId) && $this->_priceSetId) {
404 $this->add('hidden', 'priceSetId', $this->_priceSetId);
405 // build price set form.
406 $this->set('priceSetId', $this->_priceSetId);
407 if (empty($this->_ccid)) {
408 CRM_Price_BAO_PriceSet::buildPriceSet($this);
409 }
410 if ($this->_values['is_monetary'] &&
411 $this->_values['is_recur'] && empty($this->_values['pledge_id'])
412 ) {
413 self::buildRecur($this);
414 }
415 }
416
417 if ($this->_priceSetId && empty($this->_ccid)) {
418 $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
419 if ($is_quick_config) {
420 $this->_useForMember = 0;
421 $this->set('useForMember', $this->_useForMember);
422 }
423 }
424
425 //we allow premium for pledge during pledge creation only.
426 if (empty($this->_values['pledge_id']) && empty($this->_ccid)) {
427 CRM_Contribute_BAO_Premium::buildPremiumBlock($this, $this->_id, TRUE);
428 }
429
430 //don't build pledge block when mid is passed
431 if (!$this->_mid && empty($this->_ccid)) {
432 $config = CRM_Core_Config::singleton();
433 if (in_array('CiviPledge', $config->enableComponents) && !empty($this->_values['pledge_block_id'])) {
434 CRM_Pledge_BAO_PledgeBlock::buildPledgeBlock($this);
435 }
436 }
437
438 //to create an cms user
439 if (!$this->_contactID && empty($this->_ccid)) {
440 $createCMSUser = FALSE;
441
442 if ($this->_values['custom_pre_id']) {
443 $profileID = $this->_values['custom_pre_id'];
444 $createCMSUser = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_cms_user');
445 }
446
447 if (!$createCMSUser &&
448 $this->_values['custom_post_id']
449 ) {
450 if (!is_array($this->_values['custom_post_id'])) {
451 $profileIDs = [$this->_values['custom_post_id']];
452 }
453 else {
454 $profileIDs = $this->_values['custom_post_id'];
455 }
456 foreach ($profileIDs as $pid) {
457 if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $pid, 'is_cms_user')) {
458 $profileID = $pid;
459 $createCMSUser = TRUE;
460 break;
461 }
462 }
463 }
464
465 if ($createCMSUser) {
466 CRM_Core_BAO_CMSUser::buildForm($this, $profileID, TRUE);
467 }
468 }
469 if ($this->_pcpId && empty($this->_ccid)) {
470 if ($pcpSupporter = CRM_PCP_BAO_PCP::displayName($this->_pcpId)) {
471 $pcp_supporter_text = ts('This contribution is being made thanks to the effort of <strong>%1</strong>, who supports our campaign.', [1 => $pcpSupporter]);
472 // Only tell people that can also create a PCP if the contribution page has a non-empty value in the "Create Personal Campaign Page link" field.
473 $text = CRM_PCP_BAO_PCP::getPcpBlockStatus($this->_id, 'contribute');
474 if (!empty($text)) {
475 $pcp_supporter_text .= ts("You can support it as well - once you complete the donation, you will be able to create your own Personal Campaign Page!");
476 }
477 $this->assign('pcpSupporterText', $pcp_supporter_text);
478 }
479 $prms = ['id' => $this->_pcpId];
480 CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $prms, $pcpInfo);
481 if ($pcpInfo['is_honor_roll']) {
482 $this->assign('isHonor', TRUE);
483 $this->add('checkbox', 'pcp_display_in_roll', ts('Show my contribution in the public honor roll'), NULL, NULL,
484 ['onclick' => "showHideByValue('pcp_display_in_roll','','nameID|nickID|personalNoteID','block','radio',false); pcpAnonymous( );"]
485 );
486 $extraOption = ['onclick' => "return pcpAnonymous( );"];
487 $elements = [];
488 $elements[] = &$this->createElement('radio', NULL, '', ts('Include my name and message'), 0, $extraOption);
489 $elements[] = &$this->createElement('radio', NULL, '', ts('List my contribution anonymously'), 1, $extraOption);
490 $this->addGroup($elements, 'pcp_is_anonymous', NULL, '&nbsp;&nbsp;&nbsp;');
491
492 $this->add('text', 'pcp_roll_nickname', ts('Name'), ['maxlength' => 30]);
493 $this->addField('pcp_personal_note', ['entity' => 'ContributionSoft', 'context' => 'create', 'style' => 'height: 3em; width: 40em;']);
494 }
495 }
496 if (empty($this->_values['fee']) && empty($this->_ccid)) {
497 CRM_Core_Error::fatal(ts('This page does not have any price fields configured or you may not have permission for them. Please contact the site administrator for more details.'));
498 }
499
500 //we have to load confirm contribution button in template
501 //when multiple payment processor as the user
502 //can toggle with payment processor selection
503 $billingModePaymentProcessors = 0;
504 if (!empty($this->_paymentProcessors)) {
505 foreach ($this->_paymentProcessors as $key => $values) {
506 if ($values['billing_mode'] == CRM_Core_Payment::BILLING_MODE_BUTTON) {
507 $billingModePaymentProcessors++;
508 }
509 }
510 }
511
512 if ($billingModePaymentProcessors && count($this->_paymentProcessors) == $billingModePaymentProcessors) {
513 $allAreBillingModeProcessors = TRUE;
514 }
515 else {
516 $allAreBillingModeProcessors = FALSE;
517 }
518
519 if (!($allAreBillingModeProcessors && !$this->_values['is_pay_later'])) {
520 $submitButton = [
521 'type' => 'upload',
522 'name' => CRM_Utils_Array::value('is_confirm_enabled', $this->_values) ? ts('Confirm Contribution') : ts('Contribute'),
523 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
524 'isDefault' => TRUE,
525 ];
526 // Add submit-once behavior when confirm page disabled
527 if (empty($this->_values['is_confirm_enabled'])) {
528 $this->submitOnce = TRUE;
529 }
530 //change button name for updating contribution
531 if (!empty($this->_ccid)) {
532 $submitButton['name'] = ts('Confirm Payment');
533 }
534 $this->addButtons([$submitButton]);
535 }
536
537 $this->addFormRule(['CRM_Contribute_Form_Contribution_Main', 'formRule'], $this);
538 }
539
540 /**
541 * Build elements to collect information for recurring contributions.
542 *
543 *
544 * @param CRM_Core_Form $form
545 */
546 public static function buildRecur(&$form) {
547 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur');
548 $className = get_class($form);
549
550 $form->assign('is_recur_interval', CRM_Utils_Array::value('is_recur_interval', $form->_values));
551 $form->assign('is_recur_installments', CRM_Utils_Array::value('is_recur_installments', $form->_values));
552 $paymentObject = $form->getVar('_paymentObject');
553 if ($paymentObject) {
554 $form->assign('recurringHelpText', $paymentObject->getText('contributionPageRecurringHelp', [
555 'is_recur_installments' => !empty($form->_values['is_recur_installments']),
556 'is_email_receipt' => !empty($form->_values['is_email_receipt']),
557 ]));
558 }
559
560 $form->add('checkbox', 'is_recur', ts('I want to contribute this amount'), NULL);
561
562 if (!empty($form->_values['is_recur_interval']) || $className == 'CRM_Contribute_Form_Contribution') {
563 $form->add('text', 'frequency_interval', ts('Every'), $attributes['frequency_interval'] + ['aria-label' => ts('Every')]);
564 $form->addRule('frequency_interval', ts('Frequency must be a whole number (EXAMPLE: Every 3 months).'), 'integer');
565 }
566 else {
567 // make sure frequency_interval is submitted as 1 if given no choice to user.
568 $form->add('hidden', 'frequency_interval', 1);
569 }
570
571 $frUnits = CRM_Utils_Array::value('recur_frequency_unit', $form->_values);
572 if (empty($frUnits) &&
573 $className == 'CRM_Contribute_Form_Contribution'
574 ) {
575 $frUnits = implode(CRM_Core_DAO::VALUE_SEPARATOR,
576 CRM_Core_OptionGroup::values('recur_frequency_units')
577 );
578 }
579
580 $unitVals = explode(CRM_Core_DAO::VALUE_SEPARATOR, $frUnits);
581
582 // CRM 10860, display text instead of a dropdown if there's only 1 frequency unit
583 if (count($unitVals) == 1) {
584 $form->assign('one_frequency_unit', TRUE);
585 $unit = $unitVals[0];
586 $form->add('hidden', 'frequency_unit', $unit);
587 if (!empty($form->_values['is_recur_interval']) || $className == 'CRM_Contribute_Form_Contribution') {
588 $unit .= "(s)";
589 }
590 $form->assign('frequency_unit', $unit);
591 }
592 else {
593 $form->assign('one_frequency_unit', FALSE);
594 $units = [];
595 $frequencyUnits = CRM_Core_OptionGroup::values('recur_frequency_units', FALSE, FALSE, TRUE);
596 foreach ($unitVals as $key => $val) {
597 if (array_key_exists($val, $frequencyUnits)) {
598 $units[$val] = $frequencyUnits[$val];
599 if (!empty($form->_values['is_recur_interval']) || $className == 'CRM_Contribute_Form_Contribution') {
600 $units[$val] = "{$frequencyUnits[$val]}(s)";
601 }
602 }
603 }
604 $frequencyUnit = &$form->addElement('select', 'frequency_unit', NULL, $units, ['aria-label' => ts('Frequency Unit')]);
605 }
606
607 // FIXME: Ideally we should freeze select box if there is only
608 // one option but looks there is some problem /w QF freeze.
609 //if ( count( $units ) == 1 ) {
610 //$frequencyUnit->freeze( );
611 //}
612
613 $form->add('text', 'installments', ts('installments'),
614 $attributes['installments']
615 );
616 $form->addRule('installments', ts('Number of installments must be a whole number.'), 'integer');
617 }
618
619 /**
620 * Global form rule.
621 *
622 * @param array $fields
623 * The input form values.
624 * @param array $files
625 * The uploaded files if any.
626 * @param \CRM_Contribute_Form_Contribution_Main $self
627 *
628 * @return bool|array
629 * true if no errors, else array of errors
630 */
631 public static function formRule($fields, $files, $self) {
632 $errors = [];
633 $amount = self::computeAmount($fields, $self->_values);
634 if (!empty($fields['auto_renew']) && empty($fields['payment_processor_id'])) {
635 $errors['auto_renew'] = ts('You cannot have auto-renewal on if you are paying later.');
636 }
637
638 if ((!empty($fields['selectMembership']) &&
639 $fields['selectMembership'] != 'no_thanks'
640 ) ||
641 (!empty($fields['priceSetId']) &&
642 $self->_useForMember
643 )
644 ) {
645 $isTest = ($self->_action & CRM_Core_Action::PREVIEW) ? TRUE : FALSE;
646 $lifeMember = CRM_Member_BAO_Membership::getAllContactMembership($self->_membershipContactID, $isTest, TRUE);
647
648 $membershipOrgDetails = CRM_Member_BAO_MembershipType::getMembershipTypeOrganization();
649
650 $unallowedOrgs = [];
651 foreach (array_keys($lifeMember) as $memTypeId) {
652 $unallowedOrgs[] = $membershipOrgDetails[$memTypeId];
653 }
654 }
655
656 //check for atleast one pricefields should be selected
657 if (!empty($fields['priceSetId']) && empty($self->_ccid)) {
658 $priceField = new CRM_Price_DAO_PriceField();
659 $priceField->price_set_id = $fields['priceSetId'];
660 $priceField->orderBy('weight');
661 $priceField->find();
662
663 $check = [];
664 $membershipIsActive = TRUE;
665 $previousId = $otherAmount = FALSE;
666 while ($priceField->fetch()) {
667
668 if ($self->isQuickConfig() && ($priceField->name == 'contribution_amount' || $priceField->name == 'membership_amount')) {
669 $previousId = $priceField->id;
670 if ($priceField->name == 'membership_amount' && !$priceField->is_active) {
671 $membershipIsActive = FALSE;
672 }
673 }
674 if ($priceField->name == 'other_amount') {
675 if ($self->_quickConfig && empty($fields["price_{$priceField->id}"]) &&
676 array_key_exists("price_{$previousId}", $fields) && isset($fields["price_{$previousId}"]) && $self->_values['fee'][$previousId]['name'] == 'contribution_amount' && empty($fields["price_{$previousId}"])
677 ) {
678 $otherAmount = $priceField->id;
679 }
680 elseif (!empty($fields["price_{$priceField->id}"])) {
681 $otherAmountVal = CRM_Utils_Rule::cleanMoney($fields["price_{$priceField->id}"]);
682 $min = CRM_Utils_Array::value('min_amount', $self->_values);
683 $max = CRM_Utils_Array::value('max_amount', $self->_values);
684 if ($min && $otherAmountVal < $min) {
685 $errors["price_{$priceField->id}"] = ts('Contribution amount must be at least %1',
686 [1 => $min]
687 );
688 }
689 if ($max && $otherAmountVal > $max) {
690 $errors["price_{$priceField->id}"] = ts('Contribution amount cannot be more than %1.',
691 [1 => $max]
692 );
693 }
694 }
695 }
696 if (!empty($fields["price_{$priceField->id}"]) || ($previousId == $priceField->id && isset($fields["price_{$previousId}"])
697 && empty($fields["price_{$previousId}"]))
698 ) {
699 $check[] = $priceField->id;
700 }
701 }
702
703 $currentMemberships = NULL;
704 if ($membershipIsActive) {
705 $is_test = $self->_mode != 'live' ? 1 : 0;
706 $memContactID = $self->_membershipContactID;
707
708 // For anonymous user check using dedupe rule
709 // if user has Cancelled Membership
710 if (!$memContactID) {
711 $memContactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($fields, 'Individual', 'Unsupervised', [], FALSE);
712 }
713 $currentMemberships = CRM_Member_BAO_Membership::getContactsCancelledMembership($memContactID,
714 $is_test
715 );
716
717 foreach ($self->_values['fee'] as $fieldKey => $fieldValue) {
718 if ($fieldValue['html_type'] != 'Text' && CRM_Utils_Array::value('price_' . $fieldKey, $fields)) {
719 if (!is_array($fields['price_' . $fieldKey]) && isset($fieldValue['options'][$fields['price_' . $fieldKey]])) {
720 if (array_key_exists('membership_type_id', $fieldValue['options'][$fields['price_' . $fieldKey]])
721 && in_array($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'], $currentMemberships)
722 ) {
723 $errors['price_' . $fieldKey] = ts('Your %1 membership was previously cancelled and can not be renewed online. Please contact the site administrator for assistance.', [1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$fields['price_' . $fieldKey]]['membership_type_id'])]);
724 }
725 }
726 else {
727 if (is_array($fields['price_' . $fieldKey])) {
728 foreach (array_keys($fields['price_' . $fieldKey]) as $key) {
729 if (array_key_exists('membership_type_id', $fieldValue['options'][$key])
730 && in_array($fieldValue['options'][$key]['membership_type_id'], $currentMemberships)
731 ) {
732 $errors['price_' . $fieldKey] = ts('Your %1 membership was previously cancelled and can not be renewed online. Please contact the site administrator for assistance.', [1 => CRM_Member_PseudoConstant::membershipType($fieldValue['options'][$key]['membership_type_id'])]);
733 }
734 }
735 }
736 }
737 }
738 }
739 }
740
741 // CRM-12233
742 if ($membershipIsActive && !$self->_membershipBlock['is_required']
743 && $self->_values['amount_block_is_active']
744 ) {
745 $membershipFieldId = $contributionFieldId = $errorKey = $otherFieldId = NULL;
746 foreach ($self->_values['fee'] as $fieldKey => $fieldValue) {
747 // if 'No thank you' membership is selected then set $membershipFieldId
748 if ($fieldValue['name'] == 'membership_amount' && CRM_Utils_Array::value('price_' . $fieldKey, $fields) == 0) {
749 $membershipFieldId = $fieldKey;
750 }
751 elseif ($membershipFieldId) {
752 if ($fieldValue['name'] == 'other_amount') {
753 $otherFieldId = $fieldKey;
754 }
755 elseif ($fieldValue['name'] == 'contribution_amount') {
756 $contributionFieldId = $fieldKey;
757 }
758
759 if (!$errorKey || CRM_Utils_Array::value('price_' . $contributionFieldId, $fields) == '0') {
760 $errorKey = $fieldKey;
761 }
762 }
763 }
764 // $membershipFieldId is set and additional amount is 'No thank you' or NULL then throw error
765 if ($membershipFieldId && !(CRM_Utils_Array::value('price_' . $contributionFieldId, $fields, -1) > 0) && empty($fields['price_' . $otherFieldId])) {
766 $errors["price_{$errorKey}"] = ts('Additional Contribution is required.');
767 }
768 }
769 if (empty($check) && empty($self->_ccid)) {
770 if ($self->_useForMember == 1 && $membershipIsActive) {
771 $errors['_qf_default'] = ts('Select at least one option from Membership Type(s).');
772 }
773 else {
774 $errors['_qf_default'] = ts('Select at least one option from Contribution(s).');
775 }
776 }
777 if ($otherAmount && !empty($check)) {
778 $errors["price_{$otherAmount}"] = ts('Amount is required field.');
779 }
780
781 if ($self->_useForMember == 1 && !empty($check) && $membershipIsActive) {
782 $priceFieldIDS = [];
783 $priceFieldMemTypes = [];
784
785 foreach ($self->_priceSet['fields'] as $priceId => $value) {
786 if (!empty($fields['price_' . $priceId]) || ($self->_quickConfig && $value['name'] == 'membership_amount' && empty($self->_membershipBlock['is_required']))) {
787 if (!empty($fields['price_' . $priceId]) && is_array($fields['price_' . $priceId])) {
788 foreach ($fields['price_' . $priceId] as $priceFldVal => $isSet) {
789 if ($isSet) {
790 $priceFieldIDS[] = $priceFldVal;
791 }
792 }
793 }
794 elseif (!$value['is_enter_qty'] && !empty($fields['price_' . $priceId])) {
795 // The check for {!$value['is_enter_qty']} is done since, quantity fields allow entering
796 // quantity. And the quantity can't be conisdered as civicrm_price_field_value.id, CRM-9577
797 $priceFieldIDS[] = $fields['price_' . $priceId];
798 }
799
800 if (!empty($value['options'])) {
801 foreach ($value['options'] as $val) {
802 if (!empty($val['membership_type_id']) && (
803 ($fields['price_' . $priceId] == $val['id']) ||
804 (isset($fields['price_' . $priceId]) && !empty($fields['price_' . $priceId][$val['id']]))
805 )
806 ) {
807 $priceFieldMemTypes[] = $val['membership_type_id'];
808 }
809 }
810 }
811 }
812 }
813
814 if (!empty($lifeMember)) {
815 foreach ($priceFieldIDS as $priceFieldId) {
816 if (($id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) &&
817 in_array($membershipOrgDetails[$id], $unallowedOrgs)
818 ) {
819 $errors['_qf_default'] = ts('You already have a lifetime membership and cannot select a membership with a shorter term.');
820 break;
821 }
822 }
823 }
824
825 if (!empty($priceFieldIDS)) {
826 $ids = implode(',', $priceFieldIDS);
827
828 $priceFieldIDS['id'] = $fields['priceSetId'];
829 $self->set('memberPriceFieldIDS', $priceFieldIDS);
830 $count = CRM_Price_BAO_PriceSet::getMembershipCount($ids);
831 foreach ($count as $id => $occurrence) {
832 if ($occurrence > 1) {
833 $errors['_qf_default'] = ts('You have selected multiple memberships for the same organization or entity. Please review your selections and choose only one membership per entity. Contact the site administrator if you need assistance.');
834 }
835 }
836 }
837
838 if (empty($priceFieldMemTypes) && $self->_membershipBlock['is_required'] == 1) {
839 $errors['_qf_default'] = ts('Please select at least one membership option.');
840 }
841 }
842
843 CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'],
844 $fields, $lineItem
845 );
846
847 $minAmt = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $fields['priceSetId'], 'min_amount');
848 if ($fields['amount'] < 0) {
849 $errors['_qf_default'] = ts('Contribution can not be less than zero. Please select the options accordingly');
850 }
851 elseif (!empty($minAmt) && $fields['amount'] < $minAmt) {
852 $errors['_qf_default'] = ts('A minimum amount of %1 should be selected from Contribution(s).', [
853 1 => CRM_Utils_Money::format($minAmt),
854 ]);
855 }
856
857 $amount = $fields['amount'];
858 }
859
860 if (isset($fields['selectProduct']) &&
861 $fields['selectProduct'] != 'no_thanks'
862 ) {
863 $productDAO = new CRM_Contribute_DAO_Product();
864 $productDAO->id = $fields['selectProduct'];
865 $productDAO->find(TRUE);
866 $min_amount = $productDAO->min_contribution;
867
868 if ($amount < $min_amount) {
869 $errors['selectProduct'] = ts('The premium you have selected requires a minimum contribution of %1', [1 => CRM_Utils_Money::format($min_amount)]);
870 CRM_Core_Session::setStatus($errors['selectProduct']);
871 }
872 }
873
874 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
875 CRM_Contribute_BAO_ContributionRecur::validateRecurContribution($fields, $files, $self, $errors);
876
877 if (!empty($fields['is_recur']) && empty($fields['payment_processor_id'])) {
878 $errors['_qf_default'] = ts('You cannot set up a recurring contribution if you are not paying online by credit card.');
879 }
880
881 // validate PCP fields - if not anonymous, we need a nick name value
882 if ($self->_pcpId && !empty($fields['pcp_display_in_roll']) &&
883 empty($fields['pcp_is_anonymous']) &&
884 CRM_Utils_Array::value('pcp_roll_nickname', $fields) == ''
885 ) {
886 $errors['pcp_roll_nickname'] = ts('Please enter a name to include in the Honor Roll, or select \'contribute anonymously\'.');
887 }
888
889 // return if this is express mode
890 $config = CRM_Core_Config::singleton();
891 if ($self->_paymentProcessor &&
892 (int) $self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON
893 ) {
894 if (!empty($fields[$self->_expressButtonName . '_x']) || !empty($fields[$self->_expressButtonName . '_y']) ||
895 CRM_Utils_Array::value($self->_expressButtonName, $fields)
896 ) {
897 return $errors;
898 }
899 }
900
901 //validate the pledge fields.
902 if (!empty($self->_values['pledge_block_id'])) {
903 //validation for pledge payment.
904 if (!empty($self->_values['pledge_id'])) {
905 if (empty($fields['pledge_amount'])) {
906 $errors['pledge_amount'] = ts('At least one payment option needs to be checked.');
907 }
908 }
909 elseif (!empty($fields['is_pledge'])) {
910 if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_installments', $fields)) == FALSE) {
911 $errors['pledge_installments'] = ts('Please enter a valid number of pledge installments.');
912 }
913 else {
914 if (!isset($fields['pledge_installments'])) {
915 $errors['pledge_installments'] = ts('Pledge Installments is required field.');
916 }
917 elseif (CRM_Utils_Array::value('pledge_installments', $fields) == 1) {
918 $errors['pledge_installments'] = ts('Pledges consist of multiple scheduled payments. Select one-time contribution if you want to make your gift in a single payment.');
919 }
920 elseif (empty($fields['pledge_installments'])) {
921 $errors['pledge_installments'] = ts('Pledge Installments field must be > 1.');
922 }
923 }
924
925 //validation for Pledge Frequency Interval.
926 if (CRM_Utils_Rule::positiveInteger(CRM_Utils_Array::value('pledge_frequency_interval', $fields)) == FALSE) {
927 $errors['pledge_frequency_interval'] = ts('Please enter a valid Pledge Frequency Interval.');
928 }
929 else {
930 if (!isset($fields['pledge_frequency_interval'])) {
931 $errors['pledge_frequency_interval'] = ts('Pledge Frequency Interval. is required field.');
932 }
933 elseif (empty($fields['pledge_frequency_interval'])) {
934 $errors['pledge_frequency_interval'] = ts('Pledge frequency interval field must be > 0');
935 }
936 }
937 }
938 }
939
940 // if the user has chosen a free membership or the amount is less than zero
941 // i.e. we don't need to validate payment related fields or profiles.
942 if ((float) $amount <= 0.0) {
943 return $errors;
944 }
945
946 if (!isset($fields['payment_processor_id'])) {
947 $errors['payment_processor_id'] = ts('Payment Method is a required field.');
948 }
949 else {
950 CRM_Core_Payment_Form::validatePaymentInstrument(
951 $fields['payment_processor_id'],
952 $fields,
953 $errors,
954 (!$self->_isBillingAddressRequiredForPayLater ? NULL : 'billing')
955 );
956 }
957
958 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
959 if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
960 $customizedValue = CRM_Core_PseudoConstant::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
961 if ($customizedValue == $greetingType && empty($fielse[$greeting . '_custom'])) {
962 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
963 [1 => ucwords(str_replace('_', " ", $greeting))]
964 );
965 }
966 }
967 }
968
969 return empty($errors) ? TRUE : $errors;
970 }
971
972 /**
973 * Compute amount to be paid.
974 *
975 * @param array $params
976 * @param array $formValues
977 *
978 * @return int|mixed|null|string
979 */
980 public static function computeAmount($params, $formValues) {
981 $amount = 0;
982 // First clean up the other amount field if present.
983 if (isset($params['amount_other'])) {
984 $params['amount_other'] = CRM_Utils_Rule::cleanMoney($params['amount_other']);
985 }
986
987 if (CRM_Utils_Array::value('amount', $params) == 'amount_other_radio' || !empty($params['amount_other'])) {
988 $amount = $params['amount_other'];
989 }
990 elseif (!empty($params['pledge_amount'])) {
991 foreach ($params['pledge_amount'] as $paymentId => $dontCare) {
992 $amount += CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount');
993 }
994 }
995 else {
996 if (!empty($formValues['amount'])) {
997 $amountID = CRM_Utils_Array::value('amount', $params);
998
999 if ($amountID) {
1000 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1001 // function to get correct amount level consistently. Remove setting of the amount level in
1002 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1003 // to cover all variants.
1004 $params['amount_level'] = CRM_Utils_Array::value('label', $formValues[$amountID]);
1005 $amount = CRM_Utils_Array::value('value', $formValues[$amountID]);
1006 }
1007 }
1008 }
1009 return $amount;
1010 }
1011
1012 /**
1013 * Process the form submission.
1014 */
1015 public function postProcess() {
1016 // we first reset the confirm page so it accepts new values
1017 $this->controller->resetPage('Confirm');
1018
1019 // get the submitted form values.
1020 $params = $this->controller->exportValues($this->_name);
1021 $this->submit($params);
1022
1023 if (empty($this->_values['is_confirm_enabled'])) {
1024 $this->skipToThankYouPage();
1025 }
1026
1027 }
1028
1029 /**
1030 * Submit function.
1031 *
1032 * This is the guts of the postProcess made also accessible to the test suite.
1033 *
1034 * @param array $params
1035 * Submitted values.
1036 */
1037 public function submit($params) {
1038 //carry campaign from profile.
1039 if (array_key_exists('contribution_campaign_id', $params)) {
1040 $params['campaign_id'] = $params['contribution_campaign_id'];
1041 }
1042
1043 $params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
1044
1045 // @todo refactor this & leverage it from the unit tests.
1046 if (!empty($params['priceSetId'])) {
1047 $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
1048 if ($is_quick_config) {
1049 $priceField = new CRM_Price_DAO_PriceField();
1050 $priceField->price_set_id = $params['priceSetId'];
1051 $priceField->orderBy('weight');
1052 $priceField->find();
1053
1054 $priceOptions = [];
1055 while ($priceField->fetch()) {
1056 CRM_Price_BAO_PriceFieldValue::getValues($priceField->id, $priceOptions);
1057 if (($selectedPriceOptionID = CRM_Utils_Array::value("price_{$priceField->id}", $params)) != FALSE && $selectedPriceOptionID > 0) {
1058 switch ($priceField->name) {
1059 case 'membership_amount':
1060 $this->_params['selectMembership'] = $params['selectMembership'] = CRM_Utils_Array::value('membership_type_id', $priceOptions[$selectedPriceOptionID]);
1061 $this->set('selectMembership', $params['selectMembership']);
1062
1063 case 'contribution_amount':
1064 $params['amount'] = $selectedPriceOptionID;
1065 if ($priceField->name == 'contribution_amount' ||
1066 ($priceField->name == 'membership_amount' &&
1067 CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock) == 0)
1068 ) {
1069 $this->_values['amount'] = CRM_Utils_Array::value('amount', $priceOptions[$selectedPriceOptionID]);
1070 }
1071 $this->_values[$selectedPriceOptionID]['value'] = CRM_Utils_Array::value('amount', $priceOptions[$selectedPriceOptionID]);
1072 $this->_values[$selectedPriceOptionID]['label'] = CRM_Utils_Array::value('label', $priceOptions[$selectedPriceOptionID]);
1073 $this->_values[$selectedPriceOptionID]['amount_id'] = CRM_Utils_Array::value('id', $priceOptions[$selectedPriceOptionID]);
1074 $this->_values[$selectedPriceOptionID]['weight'] = CRM_Utils_Array::value('weight', $priceOptions[$selectedPriceOptionID]);
1075 break;
1076
1077 case 'other_amount':
1078 $params['amount_other'] = $selectedPriceOptionID;
1079 break;
1080 }
1081 }
1082 }
1083 }
1084 }
1085
1086 if (!empty($this->_ccid) && !empty($this->_pendingAmount)) {
1087 $params['amount'] = $this->_pendingAmount;
1088 }
1089 else {
1090 // from here on down, $params['amount'] holds a monetary value (or null) rather than an option ID
1091 $params['amount'] = self::computeAmount($params, $this->_values);
1092 }
1093
1094 $params['separate_amount'] = $params['amount'];
1095 $memFee = NULL;
1096 if (!empty($params['selectMembership'])) {
1097 if (empty($this->_membershipTypeValues)) {
1098 $this->_membershipTypeValues = CRM_Member_BAO_Membership::buildMembershipTypeValues($this,
1099 (array) $params['selectMembership']
1100 );
1101 }
1102 $membershipTypeValues = $this->_membershipTypeValues[$params['selectMembership']];
1103 $memFee = $membershipTypeValues['minimum_fee'];
1104 if (!$params['amount'] && !$this->_separateMembershipPayment) {
1105 $params['amount'] = $memFee ? $memFee : 0;
1106 }
1107 }
1108 //If the membership & contribution is used in contribution page & not separate payment
1109 $memPresent = $membershipLabel = $fieldOption = $is_quick_config = NULL;
1110 $proceFieldAmount = 0;
1111 if (property_exists($this, '_separateMembershipPayment') && $this->_separateMembershipPayment == 0) {
1112 $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
1113 if ($is_quick_config) {
1114 foreach ($this->_priceSet['fields'] as $fieldKey => $fieldVal) {
1115 if ($fieldVal['name'] == 'membership_amount' && !empty($params['price_' . $fieldKey])) {
1116 $fieldId = $fieldVal['id'];
1117 $fieldOption = $params['price_' . $fieldId];
1118 $proceFieldAmount += $fieldVal['options'][$this->_submitValues['price_' . $fieldId]]['amount'];
1119 $memPresent = TRUE;
1120 }
1121 else {
1122 if (!empty($params['price_' . $fieldKey]) && $memPresent && ($fieldVal['name'] == 'other_amount' || $fieldVal['name'] == 'contribution_amount')) {
1123 $fieldId = $fieldVal['id'];
1124 if ($fieldVal['name'] == 'other_amount') {
1125 $proceFieldAmount += $this->_submitValues['price_' . $fieldId];
1126 }
1127 elseif ($fieldVal['name'] == 'contribution_amount' && $this->_submitValues['price_' . $fieldId] > 0) {
1128 $proceFieldAmount += $fieldVal['options'][$this->_submitValues['price_' . $fieldId]]['amount'];
1129 }
1130 unset($params['price_' . $fieldId]);
1131 break;
1132 }
1133 }
1134 }
1135 }
1136 }
1137
1138 if (!isset($params['amount_other'])) {
1139 $this->set('amount_level', CRM_Utils_Array::value('amount_level', $params));
1140 }
1141
1142 if (!empty($this->_ccid)) {
1143 $this->set('lineItem', $this->_lineItem);
1144 }
1145 elseif ($priceSetId = CRM_Utils_Array::value('priceSetId', $params)) {
1146 $lineItem = [];
1147 $is_quick_config = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1148 if ($is_quick_config) {
1149 foreach ($this->_values['fee'] as $key => & $val) {
1150 if ($val['name'] == 'other_amount' && $val['html_type'] == 'Text' && !empty($params['price_' . $key])) {
1151 // Clean out any currency symbols.
1152 $params['price_' . $key] = CRM_Utils_Rule::cleanMoney($params['price_' . $key]);
1153 if ($params['price_' . $key] != 0) {
1154 foreach ($val['options'] as $optionKey => & $options) {
1155 $options['amount'] = CRM_Utils_Array::value('price_' . $key, $params);
1156 break;
1157 }
1158 }
1159 $params['price_' . $key] = 1;
1160 break;
1161 }
1162 }
1163 }
1164 $component = '';
1165 if ($this->_membershipBlock) {
1166 $component = 'membership';
1167 }
1168
1169 CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem[$priceSetId], $component, $priceSetId);
1170 if ($params['tax_amount']) {
1171 $this->set('tax_amount', $params['tax_amount']);
1172 }
1173
1174 if ($proceFieldAmount) {
1175 $lineItem[$params['priceSetId']][$fieldOption]['unit_price'] = $proceFieldAmount;
1176 $lineItem[$params['priceSetId']][$fieldOption]['line_total'] = $proceFieldAmount;
1177 if (isset($lineItem[$params['priceSetId']][$fieldOption]['tax_amount'])) {
1178 $proceFieldAmount += $lineItem[$params['priceSetId']][$fieldOption]['tax_amount'];
1179 }
1180 if (!$this->_membershipBlock['is_separate_payment']) {
1181 //require when separate membership not used
1182 $params['amount'] = $proceFieldAmount;
1183 }
1184 }
1185 $this->set('lineItem', $lineItem);
1186 }
1187
1188 if ($params['amount'] != 0 && (($this->_values['is_pay_later'] &&
1189 empty($this->_paymentProcessor) &&
1190 !array_key_exists('hidden_processor', $params)) ||
1191 empty($params['payment_processor_id']))
1192 ) {
1193 $params['is_pay_later'] = 1;
1194 }
1195 else {
1196 $params['is_pay_later'] = 0;
1197 }
1198
1199 // Would be nice to someday understand the point of this set.
1200 $this->set('is_pay_later', $params['is_pay_later']);
1201 // assign pay later stuff
1202 $this->_params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, FALSE);
1203 $this->assign('is_pay_later', $params['is_pay_later']);
1204 if ($params['is_pay_later']) {
1205 $this->assign('pay_later_text', $this->_values['pay_later_text']);
1206 $this->assign('pay_later_receipt', CRM_Utils_Array::value('pay_later_receipt', $this->_values));
1207 }
1208
1209 if ($this->_membershipBlock['is_separate_payment'] && !empty($params['separate_amount'])) {
1210 $this->set('amount', $params['separate_amount']);
1211 }
1212 else {
1213 $this->set('amount', $params['amount']);
1214 }
1215
1216 // generate and set an invoiceID for this transaction
1217 $invoiceID = md5(uniqid(rand(), TRUE));
1218 $this->set('invoiceID', $invoiceID);
1219 $params['invoiceID'] = $invoiceID;
1220 $title = !empty($this->_values['frontend_title']) ? $this->_values['frontend_title'] : $this->_values['title'];
1221 $params['description'] = ts('Online Contribution') . ': ' . ((!empty($this->_pcpInfo['title']) ? $this->_pcpInfo['title'] : $title));
1222 $params['button'] = $this->controller->getButtonName();
1223 // required only if is_monetary and valid positive amount
1224 // @todo it seems impossible for $memFee to be greater than 0 & $params['amount'] not to
1225 // be & by requiring $memFee down here we make it harder to do a sensible refactoring of the function
1226 // above (ie. extract the amount in a small function).
1227 if ($this->_values['is_monetary'] &&
1228 !empty($this->_paymentProcessor) &&
1229 ((float ) $params['amount'] > 0.0 || $memFee > 0.0)
1230 ) {
1231 // The concept of contributeMode is deprecated - as should be the 'is_monetary' setting.
1232 $this->setContributeMode();
1233 // Really this setting of $this->_params & params within it should be done earlier on in the function
1234 // probably the values determined here should be reused in confirm postProcess as there is no opportunity to alter anything
1235 // on the confirm page. However as we are dealing with a stable release we go as close to where it is used
1236 // as possible.
1237 // In general the form has a lack of clarity of the logic of why things are set on the form in some cases &
1238 // the logic around when $this->_params is used compared to other params arrays.
1239 $this->_params = array_merge($params, $this->_params);
1240 $this->setRecurringMembershipParams();
1241 if ($this->_paymentProcessor &&
1242 $this->_paymentProcessor['object']->supports('preApproval')
1243 ) {
1244 $this->handlePreApproval($this->_params);
1245 }
1246 }
1247 }
1248
1249 /**
1250 * Assign the billing mode to the template.
1251 *
1252 * This is required for legacy support for contributeMode in templates.
1253 *
1254 * The goal is to remove this parameter & use more relevant parameters.
1255 */
1256 protected function setContributeMode() {
1257 switch ($this->_paymentProcessor['billing_mode']) {
1258 case CRM_Core_Payment::BILLING_MODE_FORM:
1259 $this->set('contributeMode', 'direct');
1260 break;
1261
1262 case CRM_Core_Payment::BILLING_MODE_BUTTON:
1263 $this->set('contributeMode', 'express');
1264 break;
1265
1266 case CRM_Core_Payment::BILLING_MODE_NOTIFY:
1267 $this->set('contributeMode', 'notify');
1268 break;
1269 }
1270
1271 }
1272
1273 /**
1274 * Process confirm function and pass browser to the thank you page.
1275 */
1276 protected function skipToThankYouPage() {
1277 // call the post process hook for the main page before we switch to confirm
1278 $this->postProcessHook();
1279
1280 // build the confirm page
1281 $confirmForm = &$this->controller->_pages['Confirm'];
1282 $confirmForm->preProcess();
1283 $confirmForm->buildQuickForm();
1284
1285 // the confirmation page is valid
1286 $data = &$this->controller->container();
1287 $data['valid']['Confirm'] = 1;
1288
1289 // confirm the contribution
1290 // mainProcess calls the hook also
1291 $confirmForm->mainProcess();
1292 $qfKey = $this->controller->_key;
1293
1294 // redirect to thank you page
1295 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_ThankYou_display=1&qfKey=$qfKey", TRUE, NULL, FALSE));
1296 }
1297
1298 /**
1299 * Set form variables if contribution ID is found
1300 */
1301 public function assignFormVariablesByContributionID() {
1302 if (empty($this->_ccid)) {
1303 return;
1304 }
1305 if (!$this->getContactID()) {
1306 CRM_Core_Error::statusBounce(ts("Returning since there is no contact attached to this contribution id."));
1307 }
1308
1309 $paymentBalance = CRM_Contribute_BAO_Contribution::getContributionBalance($this->_ccid);
1310 //bounce if the contribution is not pending.
1311 if ((int) $paymentBalance <= 0) {
1312 CRM_Core_Error::statusBounce(ts("Returning since contribution has already been handled."));
1313 }
1314 if (!empty($paymentBalance)) {
1315 $this->_pendingAmount = $paymentBalance;
1316 $this->assign('pendingAmount', $this->_pendingAmount);
1317 }
1318
1319 if ($taxAmount = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_ccid, 'tax_amount')) {
1320 $this->set('tax_amount', $taxAmount);
1321 $this->assign('taxAmount', $taxAmount);
1322 }
1323
1324 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($this->_ccid);
1325 foreach (array_keys($lineItems) as $id) {
1326 $lineItems[$id]['id'] = $id;
1327 }
1328 $itemId = key($lineItems);
1329 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1330 $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1331 }
1332
1333 if (!empty($lineItems[$itemId]['price_field_id'])) {
1334 $this->_lineItem[$this->_priceSetId] = $lineItems;
1335 }
1336 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config');
1337 $this->assign('lineItem', $this->_lineItem);
1338 $this->assign('is_quick_config', $isQuickConfig);
1339 $this->assign('priceSetID', $this->_priceSetId);
1340 }
1341
1342 /**
1343 * Function for unit tests on the postProcess function.
1344 *
1345 * @param array $params
1346 */
1347 public function testSubmit($params) {
1348 $_SERVER['REQUEST_METHOD'] = 'GET';
1349 $this->controller = new CRM_Contribute_Controller_Contribution();
1350 $this->submit($params);
1351 }
1352
1353 }