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