Fix button breakage on viewContribution
[civicrm-core.git] / CRM / Contribute / Form / ContributionPage / Amount.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * form to process actions on the group aspect of Custom Data
20 */
21 class CRM_Contribute_Form_ContributionPage_Amount extends CRM_Contribute_Form_ContributionPage {
22
23 /**
24 * Contribution amount block.
25 *
26 * @var array
27 */
28 protected $_amountBlock = [];
29
30 /**
31 * Constants for number of options for data types of multiple option.
32 */
33 const NUM_OPTION = 11;
34
35 /**
36 * Set variables up before form is built.
37 */
38 public function preProcess() {
39 parent::preProcess();
40 $this->setSelectedChild('amount');
41 }
42
43 /**
44 * Build the form object.
45 */
46 public function buildQuickForm() {
47
48 // do u want to allow a free form text field for amount
49 $this->addElement('checkbox', 'is_allow_other_amount', ts('Allow other amounts'), NULL, ['onclick' => "minMax(this);showHideAmountBlock( this, 'is_allow_other_amount' );"]);
50 $this->add('text', 'min_amount', ts('Minimum Amount'), ['size' => 8, 'maxlength' => 8]);
51 $this->addRule('min_amount', ts('Please enter a valid money value (e.g. %1).', [1 => CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency('9.99')]), 'money');
52
53 $this->add('text', 'max_amount', ts('Maximum Amount'), ['size' => 8, 'maxlength' => 8]);
54 $this->addRule('max_amount', ts('Please enter a valid money value (e.g. %1).', [1 => CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency('99.99')]), 'money');
55
56 //CRM-12055
57 $this->add('text', 'amount_label', ts('Contribution Amounts Label'));
58
59 $default = [0 => NULL];
60 $this->add('hidden', "price_field_id", '', ['id' => "price_field_id"]);
61 $this->add('hidden', "price_field_other", '', ['id' => "price_field_option"]);
62 for ($i = 1; $i <= self::NUM_OPTION; $i++) {
63 // label
64 $this->add('text', "label[$i]", ts('Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'label'));
65
66 $this->add('hidden', "price_field_value[$i]", '', ['id' => "price_field_value[$i]"]);
67
68 // value
69 $this->add('text', "value[$i]", ts('Value'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'value'));
70 $this->addRule("value[$i]", ts('Please enter a valid money value (e.g. %1).', [1 => CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency('99.99')]), 'money');
71
72 // default
73 $default[$i] = NULL;
74 }
75
76 $this->addRadio('default', '', $default);
77
78 $this->addElement('checkbox', 'amount_block_is_active', ts('Contribution Amounts section enabled'), NULL, ['onclick' => "showHideAmountBlock( this, 'amount_block_is_active' );"]);
79
80 $this->addElement('checkbox', 'is_monetary', ts('Execute real-time monetary transactions'));
81
82 $paymentProcessors = CRM_Financial_BAO_PaymentProcessor::getAllPaymentProcessors('live');
83 $recurringPaymentProcessor = $futurePaymentProcessor = $paymentProcessor = [];
84
85 if (!empty($paymentProcessors)) {
86 foreach ($paymentProcessors as $id => $processor) {
87 if ($id != 0) {
88 $paymentProcessor[$id] = $processor['name'];
89 }
90 if (!empty($processor['is_recur'])) {
91 $recurringPaymentProcessor[] = $id;
92 }
93 if (!empty($processor['object']) && $processor['object']->supports('FutureRecurStartDate')) {
94 $futurePaymentProcessor[] = $id;
95 }
96 }
97 }
98 if (count($recurringPaymentProcessor)) {
99 $this->assign('recurringPaymentProcessor', $recurringPaymentProcessor);
100 }
101 if (count($futurePaymentProcessor)) {
102 $this->assign('futurePaymentProcessor', $futurePaymentProcessor);
103 }
104 if (count($paymentProcessor)) {
105 $this->assign('paymentProcessor', $paymentProcessor);
106 }
107
108 $this->addCheckBox('payment_processor', ts('Payment Processor'),
109 array_flip($paymentProcessor),
110 NULL, NULL, NULL, NULL,
111 ['&nbsp;&nbsp;', '&nbsp;&nbsp;', '&nbsp;&nbsp;', '<br/>']
112 );
113
114 //check if selected payment processor supports recurring payment
115 if (!empty($recurringPaymentProcessor)) {
116 $this->addElement('checkbox', 'is_recur', ts('Recurring Contributions'), NULL,
117 ['onclick' => "showHideByValue('is_recur',true,'recurFields','table-row','radio',false);"]
118 );
119 $this->addCheckBox('recur_frequency_unit', ts('Supported recurring units'),
120 CRM_Core_OptionGroup::values('recur_frequency_units', FALSE, FALSE, TRUE),
121 NULL, NULL, NULL, NULL,
122 ['&nbsp;&nbsp;', '&nbsp;&nbsp;', '&nbsp;&nbsp;', '<br/>'], TRUE
123 );
124 $this->addElement('checkbox', 'is_recur_interval', ts('Support recurring intervals'));
125 $this->addElement('checkbox', 'is_recur_installments', ts('Offer installments'));
126 }
127
128 // add pay later options
129 $this->addElement('checkbox', 'is_pay_later', ts('Pay later option'), NULL);
130 $this->addElement('textarea', 'pay_later_text', ts('Pay later label'),
131 CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'pay_later_text'),
132 FALSE
133 );
134 $this->add('wysiwyg', 'pay_later_receipt', ts('Pay Later Instructions'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'pay_later_receipt'));
135 $this->addElement('checkbox', 'is_billing_required', ts('Billing address required'));
136
137 //add partial payment options
138
139 // add price set fields
140 $price = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute');
141 if (CRM_Utils_System::isNull($price)) {
142 $this->assign('price', FALSE);
143 }
144 else {
145 $this->assign('price', TRUE);
146 }
147
148 $this->addField('price_set_id', [
149 'entity' => 'PriceField',
150 'options' => $price,
151 'onchange' => "showHideAmountBlock( this.value, 'price_set_id' );",
152 ]);
153
154 //CiviPledge fields.
155 if (CRM_Core_Component::isEnabled('CiviPledge')) {
156 $this->assign('civiPledge', TRUE);
157 $this->addElement('checkbox', 'is_pledge_active', ts('Pledges'),
158 NULL, ['onclick' => "showHideAmountBlock( this, 'is_pledge_active' ); return showHideByValue('is_pledge_active',true,'pledgeFields','table-row','radio',false);"]
159 );
160 $this->addCheckBox('pledge_frequency_unit', ts('Supported pledge frequencies'),
161 CRM_Core_OptionGroup::values('recur_frequency_units', FALSE, FALSE, TRUE),
162 NULL, NULL, NULL, NULL,
163 ['&nbsp;&nbsp;', '&nbsp;&nbsp;', '&nbsp;&nbsp;', '<br/>'], TRUE
164 );
165 $this->addElement('checkbox', 'is_pledge_interval', ts('Allow frequency intervals'));
166 $this->addElement('text', 'initial_reminder_day', ts('Send payment reminder'), ['size' => 3]);
167 $this->addElement('text', 'max_reminders', ts('Send up to'), ['size' => 3]);
168 $this->addElement('text', 'additional_reminder_day', ts('Send additional reminders'), ['size' => 3]);
169 if (!empty($futurePaymentProcessor)) {
170 // CRM-18854
171 $this->addElement('checkbox', 'adjust_recur_start_date', ts('Adjust Recurring Start Date'), NULL,
172 ['onclick' => "showHideByValue('adjust_recur_start_date',true,'recurDefaults','table-row','radio',false);"]
173 );
174 $this->add('datepicker', 'pledge_calendar_date', ts('Specific Calendar Date'), [], FALSE, ['time' => FALSE]);
175 $month = CRM_Utils_Date::getCalendarDayOfMonth();
176 $this->add('select', 'pledge_calendar_month', ts('Specific day of Month'), $month);
177 $pledgeDefaults = [
178 'contribution_date' => ts('Day of Contribution'),
179 'calendar_date' => ts('Specific Calendar Date'),
180 'calendar_month' => ts('Specific day of Month'),
181 ];
182 $this->addRadio('pledge_default_toggle', ts('Recurring Contribution Start Date Default'), $pledgeDefaults, ['allowClear' => FALSE], '<br/><br/>');
183 $this->addElement('checkbox', 'is_pledge_start_date_visible', ts('Show Recurring Donation Start Date?'), NULL);
184 $this->addElement('checkbox', 'is_pledge_start_date_editable', ts('Allow Edits to Recurring Donation Start date?'), NULL);
185 }
186 }
187
188 //add currency element.
189 $this->addCurrency('currency', ts('Currency'));
190
191 $this->addFormRule(['CRM_Contribute_Form_ContributionPage_Amount', 'formRule'], $this);
192
193 parent::buildQuickForm();
194 }
195
196 /**
197 * Set default values for the form. Note that in edit/view mode
198 * the default values are retrieved from the database
199 *
200 *
201 * @return array
202 */
203 public function setDefaultValues() {
204 $defaults = parent::setDefaultValues();
205
206 if (empty($defaults['pay_later_text'])) {
207 $defaults['pay_later_text'] = ts('I will send payment by check');
208 }
209
210 if (!empty($defaults['amount_block_is_active'])) {
211
212 if ($priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $this->_id, NULL)) {
213 if ($isQuick = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
214 $this->assign('isQuick', $isQuick);
215 //$priceField = CRM_Core_DAO::getFieldValue( 'CRM_Price_DAO_PriceField', $priceSetId, 'id', 'price_set_id' );
216 $options = $pFIDs = [];
217 $priceFieldParams = ['price_set_id' => $priceSetId];
218 $priceFields = CRM_Core_DAO::commonRetrieveAll('CRM_Price_DAO_PriceField', 'price_set_id', $priceSetId, $pFIDs, $return = [
219 'html_type',
220 'name',
221 'is_active',
222 'label',
223 ]);
224 foreach ($priceFields as $priceField) {
225 if ($priceField['id'] && $priceField['html_type'] == 'Radio' && $priceField['name'] == 'contribution_amount') {
226 $defaults['price_field_id'] = $priceField['id'];
227 $priceFieldOptions = CRM_Price_BAO_PriceFieldValue::getValues($priceField['id'], $options, 'id', 1);
228 if (empty($priceFieldOptions)) {
229 continue;
230 }
231 $countRow = 0;
232 $defaults['amount_label'] = $priceField['label'];
233 foreach ($options as $optionId => $optionValue) {
234 $countRow++;
235 $defaults['value'][$countRow] = $optionValue['amount'];
236 $defaults['label'][$countRow] = $optionValue['label'] ?? NULL;
237 $defaults['name'][$countRow] = $optionValue['name'] ?? NULL;
238 $defaults['weight'][$countRow] = $optionValue['weight'];
239
240 $defaults["price_field_value"][$countRow] = $optionValue['id'];
241 if ($optionValue['is_default']) {
242 $defaults['default'] = $countRow;
243 }
244 }
245 }
246 elseif ($priceField['id'] && $priceField['html_type'] == 'Text' && $priceField['name'] = 'other_amount' && $priceField['is_active']) {
247 $defaults['price_field_other'] = $priceField['id'];
248 if (!isset($defaults['amount_label'])) {
249 $defaults['amount_label'] = $priceField['label'];
250 }
251 }
252 }
253 }
254 }
255
256 if (empty($defaults['amount_label'])) {
257 $defaults['amount_label'] = ts('Contribution Amount');
258 }
259
260 if (!empty($defaults['value']) && is_array($defaults['value'])) {
261
262 // CRM-4038: fix value display
263 foreach ($defaults['value'] as & $amount) {
264 $amount = trim(CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($amount));
265 }
266 }
267 }
268
269 // fix the display of the monetary value, CRM-4038
270 if (isset($defaults['min_amount'])) {
271 $defaults['min_amount'] = CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($defaults['min_amount']);
272 }
273 if (isset($defaults['max_amount'])) {
274 $defaults['max_amount'] = CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($defaults['max_amount']);
275 }
276
277 if (!empty($defaults['payment_processor'])) {
278 $defaults['payment_processor'] = array_fill_keys(explode(CRM_Core_DAO::VALUE_SEPARATOR,
279 $defaults['payment_processor']
280 ), '1');
281 }
282 return $defaults;
283 }
284
285 /**
286 * Global form rule.
287 *
288 * @param array $fields
289 * The input form values.
290 * @param array $files
291 * The uploaded files if any.
292 * @param self $self
293 *
294 *
295 * @return bool|array
296 * true if no errors, else array of errors
297 */
298 public static function formRule($fields, $files, $self) {
299 $errors = [];
300 //as for separate membership payment we has to have
301 //contribution amount section enabled, hence to disable it need to
302 //check if separate membership payment enabled,
303 //if so disable first separate membership payment option
304 //then disable contribution amount section. CRM-3801,
305
306 $membershipBlock = new CRM_Member_DAO_MembershipBlock();
307 $membershipBlock->entity_table = 'civicrm_contribution_page';
308 $membershipBlock->entity_id = $self->_id;
309 $membershipBlock->is_active = 1;
310 $hasMembershipBlk = FALSE;
311 if ($membershipBlock->find(TRUE)) {
312 if (!empty($fields['amount_block_is_active']) &&
313 ($setID = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $self->_id, NULL, 1))
314 ) {
315 $extends = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'extends');
316 if ($extends && $extends == CRM_Core_Component::getComponentID('CiviMember')) {
317 $errors['amount_block_is_active'] = ts('You cannot use a Membership Price Set when the Contribution Amounts section is enabled. Click the Memberships tab above, and select your Membership Price Set on that form. Membership Price Sets may include additional fields for non-membership options that require an additional fee (e.g. magazine subscription) or an additional voluntary contribution.');
318 return $errors;
319 }
320 }
321 $hasMembershipBlk = TRUE;
322 if ($membershipBlock->is_separate_payment && empty($fields['amount_block_is_active'])) {
323 $errors['amount_block_is_active'] = ts('To disable Contribution Amounts section you need to first disable Separate Membership Payment option from Membership Settings.');
324 }
325
326 //CRM-16165, Don't allow reccuring contribution if membership block contain any renewable membership option
327 $membershipTypes = CRM_Utils_String::unserialize($membershipBlock->membership_types);
328 if (!empty($fields['is_recur']) && !empty($membershipTypes)) {
329 if (!$membershipBlock->is_separate_payment) {
330 $errors['is_recur'] = ts('You need to enable Separate Membership Payment when online contribution page is configured for both Membership and Recurring Contribution.');
331 }
332 elseif (count(array_filter($membershipTypes)) != 0) {
333 $errors['is_recur'] = ts('You cannot enable both Recurring Contributions and Auto-renew memberships on the same online contribution page.');
334 }
335 }
336 }
337
338 // CRM-18854 Check if recurring start date is in the future.
339 if (!empty($fields['pledge_calendar_date'])) {
340 if (date('Ymd') > date('Ymd', strtotime($fields['pledge_calendar_date']))) {
341 $errors['pledge_calendar_date'] = ts('The recurring start date cannot be prior to the current date.');
342 }
343 }
344
345 //check for the amount label (mandatory)
346 if (!empty($fields['amount_block_is_active']) && empty($fields['price_set_id']) && empty($fields['amount_label'])) {
347 $errors['amount_label'] = ts('Please enter the contribution amount label.');
348 }
349 $minAmount = $fields['min_amount'] ?? NULL;
350 $maxAmount = $fields['max_amount'] ?? NULL;
351 if (!empty($minAmount) && !empty($maxAmount)) {
352 $minAmount = CRM_Utils_Rule::cleanMoney($minAmount);
353 $maxAmount = CRM_Utils_Rule::cleanMoney($maxAmount);
354 if ((float ) $minAmount > (float ) $maxAmount) {
355 $errors['min_amount'] = ts('Minimum Amount should be less than Maximum Amount');
356 }
357 }
358
359 if (isset($fields['is_pay_later'])) {
360 if (empty($fields['pay_later_text'])) {
361 $errors['pay_later_text'] = ts('Please enter the text for the \'pay later\' checkbox displayed on the contribution form.');
362 }
363 if (empty($fields['pay_later_receipt'])) {
364 $errors['pay_later_receipt'] = ts('Please enter the instructions to be sent to the contributor when they choose to \'pay later\'.');
365 }
366 }
367 else {
368 if (!empty($fields['amount_block_is_active']) && empty($fields['payment_processor'])) {
369 $errors['payment_processor'] = ts('You have listed fixed contribution options or selected a price set, but no payment option has been selected. Please select at least one payment processor and/or enable the pay later option.');
370 }
371 }
372
373 // don't allow price set w/ membership signup, CRM-5095
374 if ($priceSetId = CRM_Utils_Array::value('price_set_id', $fields)) {
375 // don't allow price set w/ membership.
376 if ($hasMembershipBlk) {
377 $errors['price_set_id'] = ts('You cannot enable both a Contribution Price Set and Membership Signup on the same online contribution page.');
378 }
379 }
380 else {
381 if (isset($fields['is_recur'])) {
382 if (empty($fields['recur_frequency_unit'])) {
383 $errors['recur_frequency_unit'] = ts('At least one recurring frequency option needs to be checked.');
384 }
385 }
386
387 // validation for pledge fields.
388 if (!empty($fields['is_pledge_active'])) {
389 if (empty($fields['pledge_frequency_unit'])) {
390 $errors['pledge_frequency_unit'] = ts('At least one pledge frequency option needs to be checked.');
391 }
392 if (!empty($fields['is_recur'])) {
393 $errors['is_recur'] = ts('You cannot enable both Recurring Contributions AND Pledges on the same online contribution page.');
394 }
395 }
396
397 // If Contribution amount section is enabled, then
398 // Allow other amounts must be enabled OR the Fixed Contribution
399 // Contribution options must contain at least one set of values.
400 if (!empty($fields['amount_block_is_active'])) {
401 if (empty($fields['is_allow_other_amount']) &&
402 !$priceSetId
403 ) {
404 //get the values of amount block
405 $values = $fields['value'] ?? NULL;
406 $isSetRow = FALSE;
407 for ($i = 1; $i < self::NUM_OPTION; $i++) {
408 if ((isset($values[$i]) && (strlen(trim($values[$i])) > 0))) {
409 $isSetRow = TRUE;
410 }
411 }
412 if (!$isSetRow) {
413 $errors['amount_block_is_active'] = ts('If you want to enable the \'Contribution Amounts section\', you need to either \'Allow Other Amounts\' and/or enter at least one row in the \'Fixed Contribution Amounts\' table.');
414 }
415 }
416 }
417 }
418
419 if (!empty($fields['payment_processor']) && $financialType = CRM_Contribute_BAO_Contribution::validateFinancialType($self->_defaultValues['financial_type_id'])) {
420 $errors['payment_processor'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
421 }
422
423 return $errors;
424 }
425
426 /**
427 * Process the form.
428 */
429 public function postProcess() {
430 // get the submitted form values.
431 $params = $this->controller->exportValues($this->_name);
432
433 //update 'is_billing_required'
434 if (empty($params['is_pay_later'])) {
435 $params['is_billing_required'] = 0;
436 }
437
438 if (array_key_exists('payment_processor', $params)) {
439 if (array_key_exists(CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessor', 'AuthNet',
440 'id', 'payment_processor_type_id'
441 ),
442 CRM_Utils_Array::value('payment_processor', $params)
443 )) {
444 CRM_Core_Session::setStatus(ts(' Please note that the Authorize.net payment processor only allows recurring contributions and auto-renew memberships with payment intervals from 7-365 days or 1-12 months (i.e. not greater than 1 year).'), '', 'alert');
445 }
446 }
447
448 // check for price set.
449 $priceSetID = $params['price_set_id'] ?? NULL;
450
451 // get required fields.
452 $fields = [
453 'id' => $this->_id,
454 'is_recur' => FALSE,
455 'min_amount' => "null",
456 'max_amount' => "null",
457 'is_monetary' => FALSE,
458 'is_pay_later' => FALSE,
459 'is_billing_required' => FALSE,
460 'is_recur_interval' => FALSE,
461 'is_recur_installments' => FALSE,
462 'recur_frequency_unit' => "null",
463 'default_amount_id' => "null",
464 'is_allow_other_amount' => FALSE,
465 'amount_block_is_active' => FALSE,
466 ];
467 $resetFields = [];
468 if ($priceSetID) {
469 $resetFields = ['min_amount', 'max_amount', 'is_allow_other_amount'];
470 }
471
472 if (empty($params['is_recur'])) {
473 $resetFields = array_merge($resetFields, ['is_recur_interval', 'recur_frequency_unit']);
474 }
475
476 foreach ($fields as $field => $defaultVal) {
477 $val = CRM_Utils_Array::value($field, $params, $defaultVal);
478 if (in_array($field, $resetFields)) {
479 $val = $defaultVal;
480 }
481
482 if (in_array($field, [
483 'min_amount',
484 'max_amount',
485 ])) {
486 $val = CRM_Utils_Rule::cleanMoney($val);
487 }
488
489 $params[$field] = $val;
490 }
491
492 if ($params['is_recur']) {
493 $params['recur_frequency_unit'] = implode(CRM_Core_DAO::VALUE_SEPARATOR,
494 array_keys($params['recur_frequency_unit'])
495 );
496 $params['is_recur_interval'] = CRM_Utils_Array::value('is_recur_interval', $params, FALSE);
497 $params['is_recur_installments'] = CRM_Utils_Array::value('is_recur_installments', $params, FALSE);
498 }
499
500 if (!empty($params['adjust_recur_start_date'])) {
501 $fieldValue = '';
502 $pledgeDateFields = [
503 'calendar_date' => 'pledge_calendar_date',
504 'calendar_month' => 'pledge_calendar_month',
505 ];
506 if ($params['pledge_default_toggle'] == 'contribution_date') {
507 $fieldValue = json_encode(['contribution_date' => date('Y-m-d')]);
508 }
509 else {
510 foreach ($pledgeDateFields as $key => $pledgeDateField) {
511 if (!empty($params[$pledgeDateField]) && $params['pledge_default_toggle'] == $key) {
512 $fieldValue = json_encode([$key => $params[$pledgeDateField]]);
513 break;
514 }
515 }
516 }
517 $params['pledge_start_date'] = $fieldValue;
518 }
519 else {
520 $params['pledge_start_date'] = '';
521 $params['adjust_recur_start_date'] = 0;
522 $params['is_pledge_start_date_visible'] = 0;
523 $params['is_pledge_start_date_editable'] = 0;
524 }
525 if (empty($params['is_pledge_start_date_visible'])) {
526 $params['is_pledge_start_date_visible'] = 0;
527 }
528 if (empty($params['is_pledge_start_date_editable'])) {
529 $params['is_pledge_start_date_editable'] = 0;
530 }
531
532 if (array_key_exists('payment_processor', $params) &&
533 !CRM_Utils_System::isNull($params['payment_processor'])
534 ) {
535 $params['payment_processor'] = array_keys($params['payment_processor']);
536 }
537 else {
538 $params['payment_processor'] = 'null';
539 }
540
541 $contributionPage = CRM_Contribute_BAO_ContributionPage::create($params);
542 $contributionPageID = $contributionPage->id;
543
544 // prepare for data cleanup.
545 $deleteAmountBlk = $deletePledgeBlk = $deletePriceSet = FALSE;
546 if ($this->_priceSetID) {
547 $deletePriceSet = TRUE;
548 }
549 if ($this->_pledgeBlockID) {
550 $deletePledgeBlk = TRUE;
551 }
552 if (!empty($this->_amountBlock)) {
553 $deleteAmountBlk = TRUE;
554 }
555
556 if ($contributionPageID) {
557
558 if (!empty($params['amount_block_is_active'])) {
559 // handle price set.
560 if ($priceSetID) {
561 // add/update price set.
562 $deletePriceSet = FALSE;
563 if (!empty($params['price_field_id']) || !empty($params['price_field_other'])) {
564 $deleteAmountBlk = TRUE;
565 }
566
567 CRM_Price_BAO_PriceSet::addTo('civicrm_contribution_page', $contributionPageID, $priceSetID);
568 }
569 else {
570
571 $deletePriceSet = FALSE;
572 // process contribution amount block
573 $deleteAmountBlk = FALSE;
574
575 $labels = $params['label'] ?? NULL;
576 $values = $params['value'] ?? NULL;
577 $default = $params['default'] ?? NULL;
578
579 $options = [];
580 for ($i = 1; $i < self::NUM_OPTION; $i++) {
581 if (isset($values[$i]) &&
582 (strlen(trim($values[$i])) > 0)
583 ) {
584 $values[$i] = $params['value'][$i] = CRM_Utils_Rule::cleanMoney(trim($values[$i]));
585 $options[] = [
586 'label' => trim($labels[$i]),
587 'value' => $values[$i],
588 'weight' => $i,
589 'is_active' => 1,
590 'is_default' => $default == $i,
591 ];
592 }
593 }
594 /* || !empty($params['price_field_value']) || CRM_Utils_Array::value( 'price_field_other', $params )*/
595 if (!empty($options) || !empty($params['is_allow_other_amount'])) {
596 $fieldParams['is_quick_config'] = 1;
597 $noContriAmount = NULL;
598 $usedPriceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $this->_id, 3);
599 if (!(!empty($params['price_field_id']) || !empty($params['price_field_other'])) && !$usedPriceSetId) {
600 $pageTitle = strtolower(CRM_Utils_String::munge($this->_values['title'], '_', 245));
601 $setParams['title'] = $this->_values['title'];
602 if (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $pageTitle, 'id', 'name')) {
603 $setParams['name'] = $pageTitle;
604 }
605 elseif (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $pageTitle . '_' . $this->_id, 'id', 'name')) {
606 $setParams['name'] = $pageTitle . '_' . $this->_id;
607 }
608 else {
609 $timeSec = explode(".", microtime(TRUE));
610 $setParams['name'] = $pageTitle . '_' . date('is', $timeSec[0]) . $timeSec[1];
611 }
612 $setParams['is_quick_config'] = 1;
613 $setParams['financial_type_id'] = $this->_values['financial_type_id'] ?? NULL;
614 $setParams['extends'] = CRM_Core_Component::getComponentID('CiviContribute');
615 $priceSet = CRM_Price_BAO_PriceSet::create($setParams);
616 $priceSetId = $priceSet->id;
617 }
618 elseif ($usedPriceSetId && empty($params['price_field_id'])) {
619 $priceSetId = $usedPriceSetId;
620 }
621 else {
622 if ($priceFieldId = CRM_Utils_Array::value('price_field_id', $params)) {
623 foreach ($params['price_field_value'] as $arrayID => $fieldValueID) {
624 if (empty($params['label'][$arrayID]) && empty($params['value'][$arrayID]) && !empty($fieldValueID)) {
625 CRM_Price_BAO_PriceFieldValue::setIsActive($fieldValueID, '0');
626 unset($params['price_field_value'][$arrayID]);
627 }
628 }
629 if (implode('', $params['price_field_value'])) {
630 $fieldParams['id'] = $params['price_field_id'] ?? NULL;
631 $fieldParams['option_id'] = $params['price_field_value'];
632 }
633 else {
634 $noContriAmount = 0;
635 CRM_Price_BAO_PriceField::setIsActive($priceFieldId, '0');
636 }
637 }
638 else {
639 $priceFieldId = $params['price_field_other'] ?? NULL;
640 }
641 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $priceFieldId, 'price_set_id');
642 }
643 CRM_Price_BAO_PriceSet::addTo('civicrm_contribution_page', $this->_id, $priceSetId);
644 if (!empty($options)) {
645 $editedFieldParams = [
646 'price_set_id' => $priceSetId,
647 'name' => 'contribution_amount',
648 ];
649 $editedResults = [];
650 $noContriAmount = 1;
651 CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
652 if (empty($editedResults['id'])) {
653 $fieldParams['name'] = strtolower(CRM_Utils_String::munge("Contribution Amount", '_', 245));
654 }
655 else {
656 $fieldParams['id'] = $editedResults['id'] ?? NULL;
657 }
658
659 $fieldParams['price_set_id'] = $priceSetId;
660 $fieldParams['is_active'] = 1;
661 $fieldParams['weight'] = 2;
662
663 if (!empty($params['is_allow_other_amount'])) {
664 $fieldParams['is_required'] = 0;
665 }
666 else {
667 $fieldParams['is_required'] = 1;
668 }
669 $fieldParams['label'] = $params['amount_label'];
670 $fieldParams['html_type'] = 'Radio';
671 $fieldParams['option_label'] = $params['label'];
672 $fieldParams['option_amount'] = $params['value'];
673 $fieldParams['financial_type_id'] = $this->_values['financial_type_id'] ?? NULL;
674 foreach ($options as $value) {
675 $fieldParams['option_weight'][$value['weight']] = $value['weight'];
676 }
677 $fieldParams['default_option'] = $params['default'];
678 $priceField = CRM_Price_BAO_PriceField::create($fieldParams);
679 }
680 if (!empty($params['is_allow_other_amount']) && empty($params['price_field_other'])) {
681 $editedFieldParams = [
682 'price_set_id' => $priceSetId,
683 'name' => 'other_amount',
684 ];
685 $editedResults = [];
686
687 CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
688
689 if (!$priceFieldID = CRM_Utils_Array::value('id', $editedResults)) {
690 $fieldParams = [
691 'name' => 'other_amount',
692 'label' => ts('Other Amount'),
693 'price_set_id' => $priceSetId,
694 'html_type' => 'Text',
695 'financial_type_id' => $this->_values['financial_type_id'] ?? NULL,
696 'is_display_amounts' => 0,
697 'weight' => 3,
698 ];
699 $fieldParams['option_weight'][1] = 1;
700 $fieldParams['option_amount'][1] = 1;
701 if (!$noContriAmount) {
702 $fieldParams['is_required'] = 1;
703 $fieldParams['option_label'][1] = $fieldParams['label'] = $params['amount_label'];
704 }
705 else {
706 $fieldParams['is_required'] = 0;
707 $fieldParams['option_label'][1] = $fieldParams['label'] = ts('Other Amount');
708 }
709
710 $priceField = CRM_Price_BAO_PriceField::create($fieldParams);
711 }
712 else {
713 if (empty($editedResults['is_active'])) {
714 $fieldParams = $editedResults;
715 if (!$noContriAmount) {
716 $priceFieldValueID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldID, 'id', 'price_field_id');
717 CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldValueID, 'label', $params['amount_label']);
718 $fieldParams = [
719 'is_required' => 1,
720 'label' => $params['amount_label'],
721 'id' => $priceFieldID,
722 ];
723 }
724 $fieldParams['is_active'] = 1;
725 $priceField = CRM_Price_BAO_PriceField::add($fieldParams);
726 }
727 }
728 }
729 elseif (empty($params['is_allow_other_amount']) && !empty($params['price_field_other'])) {
730 CRM_Price_BAO_PriceField::setIsActive($params['price_field_other'], '0');
731 }
732 elseif ($priceFieldID = CRM_Utils_Array::value('price_field_other', $params)) {
733 $priceFieldValueID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldID, 'id', 'price_field_id');
734 if (!$noContriAmount) {
735 $fieldParams = [
736 'is_required' => 1,
737 'label' => $params['amount_label'],
738 'id' => $priceFieldID,
739 ];
740 CRM_Price_BAO_PriceField::add($fieldParams);
741 CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldValueID, 'label', $params['amount_label']);
742 }
743 else {
744 CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceField', $priceFieldID, 'is_required', 0);
745 CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldValueID, 'label', ts('Other Amount'));
746 }
747 }
748 }
749
750 if (!empty($params['is_pledge_active'])) {
751 $deletePledgeBlk = FALSE;
752 $pledgeBlockParams = [
753 'entity_id' => $contributionPageID,
754 'entity_table' => 'civicrm_contribution_page',
755 ];
756 if ($this->_pledgeBlockID) {
757 $pledgeBlockParams['id'] = $this->_pledgeBlockID;
758 }
759 $pledgeBlock = [
760 'pledge_frequency_unit',
761 'max_reminders',
762 'initial_reminder_day',
763 'additional_reminder_day',
764 'pledge_start_date',
765 'is_pledge_start_date_visible',
766 'is_pledge_start_date_editable',
767 ];
768 foreach ($pledgeBlock as $key) {
769 $pledgeBlockParams[$key] = $params[$key] ?? NULL;
770 }
771 $pledgeBlockParams['is_pledge_interval'] = CRM_Utils_Array::value('is_pledge_interval',
772 $params, FALSE
773 );
774 $pledgeBlockParams['pledge_start_date'] = CRM_Utils_Array::value('pledge_start_date',
775 $params, FALSE
776 );
777 // create pledge block.
778 CRM_Pledge_BAO_PledgeBlock::create($pledgeBlockParams);
779 }
780 }
781 }
782 else {
783 if (!empty($params['price_field_id']) || !empty($params['price_field_other'])) {
784 $usedPriceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $this->_id, 3);
785 if ($usedPriceSetId) {
786 if (!empty($params['price_field_id'])) {
787 CRM_Price_BAO_PriceField::setIsActive($params['price_field_id'], '0');
788 }
789 if (!empty($params['price_field_other'])) {
790 CRM_Price_BAO_PriceField::setIsActive($params['price_field_other'], '0');
791 }
792 }
793 else {
794 $deleteAmountBlk = TRUE;
795 $deletePriceSet = TRUE;
796 }
797 }
798 }
799
800 // delete pledge block.
801 if ($deletePledgeBlk) {
802 CRM_Pledge_BAO_PledgeBlock::deletePledgeBlock($this->_pledgeBlockID);
803 }
804
805 // delete previous price set.
806 if ($deletePriceSet) {
807 CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution_page', $contributionPageID);
808 }
809
810 if ($deleteAmountBlk) {
811 $priceField = !empty($params['price_field_id']) ? $params['price_field_id'] : CRM_Utils_Array::value('price_field_other', $params);
812 if ($priceField) {
813 $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $priceField, 'price_set_id');
814 CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
815 }
816 }
817 }
818 parent::endPostProcess();
819 }
820
821 /**
822 * Return a descriptive name for the page, used in wizard header
823 *
824 * @return string
825 */
826 public function getTitle() {
827 return ts('Amounts');
828 }
829
830 }