[NFC] comment fixes relating to doc blocks, spelling
[civicrm-core.git] / CRM / Upgrade / Snapshot / V4p2 / Price / BAO / Field.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2018
32 */
33
34 /**
35 * Business objects for managing price fields.
36 */
37 class CRM_Upgrade_Snapshot_V4p2_Price_BAO_Field extends CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field {
38
39 protected $_options;
40
41 /**
42 * Takes an associative array and creates a price field object.
43 *
44 * the function extract all the params it needs to initialize the create a
45 * price field object. the params array could contain additional unused name/value
46 * pairs
47 *
48 * @param array $params
49 * (reference ) an assoc array of name/value pairs.
50 *
51 * @return CRM_Upgrade_Snapshot_V4p2_Price_BAO_Field
52 */
53 public static function &add(&$params) {
54 $priceFieldBAO = new CRM_Upgrade_Snapshot_V4p2_Price_BAO_Field();
55
56 $priceFieldBAO->copyValues($params);
57
58 if ($id = CRM_Utils_Array::value('id', $params)) {
59 $priceFieldBAO->id = $id;
60 }
61
62 $priceFieldBAO->save();
63 return $priceFieldBAO;
64 }
65
66 /**
67 * Takes an associative array and creates a price field object.
68 *
69 * This function is invoked from within the web form layer and also from the api layer
70 *
71 * @param array $params
72 * (reference) an assoc array of name/value pairs.
73 *
74 * @return CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field
75 */
76 public static function create(&$params) {
77
78 $transaction = new CRM_Core_Transaction();
79
80 $priceField = self::add($params);
81
82 if (is_a($priceField, 'CRM_Core_Error')) {
83 $transaction->rollback();
84 return $priceField;
85 }
86
87 $options = $optionsIds = array();
88 $maxIndex = CRM_Price_Form_Field::NUM_OPTION;
89
90 if ($priceField->html_type == 'Text') {
91 $maxIndex = 1;
92
93 $fieldValue = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_FieldValue();
94 $fieldValue->price_field_id = $priceField->id;
95
96 // update previous field values( if any )
97 if ($fieldValue->find(TRUE)) {
98 $optionsIds['id'] = $fieldValue->id;
99 }
100 }
101 $defaultArray = array();
102 if ($params['html_type'] == 'CheckBox' && isset($params['default_checkbox_option'])) {
103 $tempArray = array_keys($params['default_checkbox_option']);
104 foreach ($tempArray as $v) {
105 if ($params['option_amount'][$v]) {
106 $defaultArray[$v] = 1;
107 }
108 }
109 }
110 else {
111 if (!empty($params['default_option'])) {
112 $defaultArray[$params['default_option']] = 1;
113 }
114 }
115
116 for ($index = 1; $index <= $maxIndex; $index++) {
117
118 if (array_key_exists('option_amount', $params) &&
119 array_key_exists($index, $params['option_amount']) &&
120 (CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_label', $params)) || !empty($params['is_quick_config'])) &&
121 !CRM_Utils_System::isNull($params['option_amount'][$index])
122 ) {
123 $options = array(
124 'price_field_id' => $priceField->id,
125 'label' => trim($params['option_label'][$index]),
126 'name' => CRM_Utils_String::munge($params['option_label'][$index], '_', 64),
127 'amount' => CRM_Utils_Rule::cleanMoney(trim($params['option_amount'][$index])),
128 'count' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_count', $params), NULL),
129 'max_value' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_max_value', $params), NULL),
130 'description' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_description', $params), NULL),
131 'membership_type_id' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('membership_type_id', $params), NULL),
132 'weight' => $params['option_weight'][$index],
133 'is_active' => 1,
134 'is_default' => CRM_Utils_Array::value($params['option_weight'][$index], $defaultArray) ? $defaultArray[$params['option_weight'][$index]] : 0,
135 );
136
137 if ($opIds = CRM_Utils_Array::value('option_id', $params)) {
138 if ($opId = CRM_Utils_Array::value($index, $opIds)) {
139 $optionsIds['id'] = $opId;
140 }
141 else {
142 $optionsIds['id'] = NULL;
143 }
144 }
145 CRM_Upgrade_Snapshot_V4p2_Price_BAO_FieldValue::create($options, $optionsIds);
146 }
147 }
148
149 $transaction->commit();
150 return $priceField;
151 }
152
153 /**
154 * Fetch object based on array of properties.
155 *
156 * @param array $params
157 * (reference ) an assoc array of name/value pairs.
158 * @param array $defaults
159 * (reference ) an assoc array to hold the flattened values.
160 *
161 * @return CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field
162 */
163 public static function retrieve(&$params, &$defaults) {
164 return CRM_Core_DAO::commonRetrieve('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field', $params, $defaults);
165 }
166
167 /**
168 * Update the is_active flag in the db.
169 *
170 * @param int $id
171 * Id of the database record.
172 * @param bool $is_active
173 * Value we want to set the is_active field.
174 *
175 * @return bool
176 * true if we found and updated the object, else false
177 */
178 public static function setIsActive($id, $is_active) {
179 return CRM_Core_DAO::setFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field', $id, 'is_active', $is_active);
180 }
181
182 /**
183 * Get the field title.
184 *
185 * @param int $id
186 * Id of field.
187 *
188 * @return string
189 * name
190 */
191 public static function getTitle($id) {
192 return CRM_Core_DAO::getFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field', $id, 'label');
193 }
194
195 /**
196 * This function for building custom fields.
197 *
198 * @param CRM_Core_Form $qf
199 * Form object (reference).
200 * @param string $elementName
201 * Name of the custom field.
202 * @param int $fieldId
203 * @param bool $inactiveNeeded
204 * @param bool $useRequired
205 * True if required else false.
206 * @param string $label
207 * Label for custom field.
208 * @param null $fieldOptions
209 * @param array $freezeOptions
210 *
211 * @return null
212 */
213 public static function addQuickFormElement(
214 &$qf,
215 $elementName,
216 $fieldId,
217 $inactiveNeeded,
218 $useRequired = TRUE,
219 $label = NULL,
220 $fieldOptions = NULL,
221 $freezeOptions = array()
222 ) {
223
224 $field = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field();
225 $field->id = $fieldId;
226 if (!$field->find(TRUE)) {
227 /* FIXME: failure! */
228
229 return NULL;
230 }
231
232 $otherAmount = $qf->get('values');
233 $config = CRM_Core_Config::singleton();
234 $qf->assign('currencySymbol', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Currency', $config->defaultCurrency, 'symbol', 'name'));
235 // get currency name for price field and option attributes
236 $currencyName = $config->defaultCurrency;
237
238 if (!isset($label)) {
239 $label = (property_exists($qf, '_membershipBlock') && !empty($qf->_membershipBlock['is_separate_payment']) && $field->name == 'contribution_amount' && empty($otherAmount['is_allow_other_amount'])) ? ts('Additional Contribution') : $field->label;
240 }
241
242 if ($field->name == 'contribution_amount') {
243 $qf->_contributionAmount = 1;
244 }
245
246 if (isset($qf->_online) && $qf->_online) {
247 $useRequired = FALSE;
248 }
249
250 $customOption = $fieldOptions;
251 if (!is_array($customOption)) {
252 $customOption = CRM_Upgrade_Snapshot_V4p2_Price_BAO_Field::getOptions($field->id, $inactiveNeeded);
253 }
254
255 //use value field.
256 $valueFieldName = 'amount';
257 $seperator = '|';
258 switch ($field->html_type) {
259 case 'Text':
260 $optionKey = key($customOption);
261 $count = CRM_Utils_Array::value('count', $customOption[$optionKey], '');
262 $max_value = CRM_Utils_Array::value('max_value', $customOption[$optionKey], '');
263 $priceVal = implode($seperator, array($customOption[$optionKey][$valueFieldName], $count, $max_value));
264
265 $extra = array();
266 if (property_exists($qf, '_quickConfig') && $qf->_quickConfig && property_exists($qf, '_contributionAmount') && $qf->_contributionAmount) {
267 $qf->assign('priceset', $elementName);
268 $extra = array('onclick' => 'useAmountOther();');
269 }
270
271 // if separate membership payment is used with quick config priceset then change the other amount label
272 if (property_exists($qf, '_membershipBlock') && !empty($qf->_membershipBlock['is_separate_payment']) && $qf->_quickConfig && $field->name == 'other_amount' && !property_exists($qf, '_contributionAmount')) {
273 $label = ts('Additional Contribution');
274 $useRequired = 0;
275 }
276 elseif (!empty($fieldOptions[$optionKey]['label'])) {
277 $label = $fieldOptions[$optionKey]['label'];
278 }
279
280 if ($field->is_display_amounts) {
281 $label .= '&nbsp;-&nbsp;';
282 $label .= CRM_Utils_Money::format(CRM_Utils_Array::value($valueFieldName, $customOption[$optionKey]));
283 }
284
285 $element = &$qf->add('text', $elementName, $label,
286 array_merge($extra,
287 array(
288 'price' => json_encode(array($optionKey, $priceVal)),
289 'size' => '4',
290 )
291 ),
292 $useRequired && $field->is_required
293 );
294
295 // CRM-6902
296 if (in_array($optionKey, $freezeOptions)) {
297 $element->freeze();
298 }
299
300 //CRM-10117
301 if (property_exists($qf, '_quickConfig') && $qf->_quickConfig) {
302 $message = ts("Please enter a valid amount.");
303 $type = "money";
304 }
305 else {
306 $message = ts('%1 must be an integer (whole number).', array(1 => $label));
307 $type = "positiveInteger";
308 }
309 // integers will have numeric rule applied to them.
310 $qf->addRule($elementName, $message, $type);
311 break;
312
313 case 'Radio':
314 $choice = array();
315
316 if (property_exists($qf, '_quickConfig') && $qf->_quickConfig && property_exists($qf, '_contributionAmount') && $qf->_contributionAmount) {
317 $qf->assign('contriPriceset', $elementName);
318 }
319
320 foreach ($customOption as $opId => $opt) {
321 if ($field->is_display_amounts) {
322 $opt['label'] = !empty($opt['label']) ? $opt['label'] . '&nbsp;-&nbsp;' : '';
323 $opt['label'] .= CRM_Utils_Money::format($opt[$valueFieldName]);
324 }
325 $count = CRM_Utils_Array::value('count', $opt, '');
326 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
327 $priceVal = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
328 $extra = array(
329 'price' => json_encode(array($elementName, $priceVal)),
330 'data-amount' => $opt[$valueFieldName],
331 'data-currency' => $currencyName,
332 );
333 if (property_exists($qf, '_quickConfig') && $qf->_quickConfig && $field->name == 'contribution_amount') {
334 $extra += array('onclick' => 'clearAmountOther();');
335 }
336 elseif (property_exists($qf, '_quickConfig') && $qf->_quickConfig && $field->name == 'membership_amount') {
337 $extra += array(
338 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
339 'membership-type' => $opt['membership_type_id'],
340 );
341 $qf->assign('membershipFieldID', $field->id);
342 }
343 $choice[$opId] = $qf->createElement('radio', NULL, '', $opt['label'], $opt['id'], $extra);
344
345 // CRM-6902
346 if (in_array($opId, $freezeOptions)) {
347 $choice[$opId]->freeze();
348 }
349 }
350
351 if (property_exists($qf, '_membershipBlock') && !empty($qf->_membershipBlock['is_separate_payment']) && $field->name == 'contribution_amount') {
352 $choice[] = $qf->createElement('radio', NULL, '', 'No thank you', '-1',
353 array(
354 'onclick' => 'clearAmountOther();',
355 )
356 );
357 }
358
359 if (!$field->is_required) {
360 // add "none" option
361 if (!empty($otherAmount['is_allow_other_amount']) && $field->name == 'contribution_amount') {
362 $none = ts('Other Amount');
363 }
364 elseif (property_exists($qf, '_membershipBlock') && empty($qf->_membershipBlock['is_required']) && $field->name == 'membership_amount') {
365 $none = ts('No thank you');
366 }
367 else {
368 $none = ts('-none-');
369 }
370
371 $choice[] = $qf->createElement('radio', NULL, '', $none, '0',
372 array('price' => json_encode(array($elementName, "0")))
373 );
374 }
375
376 $element = &$qf->addGroup($choice, $elementName, $label);
377
378 // make contribution field required for quick config when membership block is enabled
379 if (($field->name == 'contribution_amount' || $field->name == 'membership_amount') && property_exists($qf, '_membershipBlock') && !empty($qf->_membershipBlock) && !$field->is_required) {
380 $useRequired = $field->is_required = TRUE;
381 }
382
383 if ($useRequired && $field->is_required) {
384 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
385 }
386 break;
387
388 case 'Select':
389 $selectOption = $allowedOptions = $priceVal = array();
390
391 foreach ($customOption as $opt) {
392 $count = CRM_Utils_Array::value('count', $opt, '');
393 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
394 $priceVal[$opt['id']] = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
395
396 if ($field->is_display_amounts) {
397 $opt['label'] .= '&nbsp;-&nbsp;';
398 $opt['label'] .= CRM_Utils_Money::format($opt[$valueFieldName]);
399 }
400 $selectOption[$opt['id']] = $opt['label'];
401
402 if (!in_array($opt['id'], $freezeOptions)) {
403 $allowedOptions[] = $opt['id'];
404 }
405 }
406 $element = &$qf->add('select', $elementName, $label,
407 array('' => ts('- select -')) + $selectOption,
408 $useRequired && $field->is_required,
409 array('price' => json_encode($priceVal))
410 );
411
412 // CRM-6902
413 $button = substr($qf->controller->getButtonName(), -4);
414 if (!empty($freezeOptions) && $button != 'skip') {
415 $qf->addRule($elementName, ts('Sorry, this option is currently sold out.'), 'regex', "/" . implode('|', $allowedOptions) . "/");
416 }
417 break;
418
419 case 'CheckBox':
420
421 $check = array();
422 foreach ($customOption as $opId => $opt) {
423 $count = CRM_Utils_Array::value('count', $opt, '');
424 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
425 $priceVal = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
426
427 if ($field->is_display_amounts) {
428 $opt['label'] .= '&nbsp;-&nbsp;';
429 $opt['label'] .= CRM_Utils_Money::format($opt[$valueFieldName]);
430 }
431 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
432 array(
433 'price' => json_encode(array($opt['id'], $priceVal)),
434 'data-amount' => $opt[$valueFieldName],
435 'data-currency' => $currencyName,
436 )
437 );
438
439 // CRM-6902
440 if (in_array($opId, $freezeOptions)) {
441 $check[$opId]->freeze();
442 }
443 }
444 $element = &$qf->addGroup($check, $elementName, $label);
445 if ($useRequired && $field->is_required) {
446 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
447 }
448 break;
449 }
450 if (isset($qf->_online) && $qf->_online) {
451 $element->freeze();
452 }
453 }
454
455 /**
456 * Retrieve a list of options for the specified field.
457 *
458 * @param int $fieldId
459 * Price field ID.
460 * @param bool $inactiveNeeded
461 * Include inactive options.
462 * @param bool $reset
463 * Ignore stored values\.
464 *
465 * @return array
466 * array of options
467 */
468 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE) {
469 static $options = array();
470
471 if ($reset || empty($options[$fieldId])) {
472 $values = array();
473 CRM_Upgrade_Snapshot_V4p2_Price_BAO_FieldValue::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
474 $options[$fieldId] = $values;
475 }
476
477 return $options[$fieldId];
478 }
479
480 /**
481 * @param $optionLabel
482 * @param int $fid
483 *
484 * @return mixed
485 */
486 public static function getOptionId($optionLabel, $fid) {
487 if (!$optionLabel || !$fid) {
488 return;
489 }
490
491 $optionGroupName = "civicrm_price_field.amount.{$fid}";
492
493 $query = "
494 SELECT
495 option_value.id as id
496 FROM
497 civicrm_option_value option_value,
498 civicrm_option_group option_group
499 WHERE
500 option_group.name = %1
501 AND option_group.id = option_value.option_group_id
502 AND option_value.label = %2";
503
504 $dao = CRM_Core_DAO::executeQuery($query, array(
505 1 => array($optionGroupName, 'String'),
506 2 => array($optionLabel, 'String'),
507 ));
508
509 while ($dao->fetch()) {
510 return $dao->id;
511 }
512 }
513
514 /**
515 * Delete the price set field.
516 *
517 * @param int $id
518 * Field Id.
519 *
520 * @return mixed
521 * Boolean-ish
522 */
523 public static function deleteField($id) {
524 $field = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field();
525 $field->id = $id;
526
527 if ($field->find(TRUE)) {
528 // delete the options for this field
529 CRM_Upgrade_Snapshot_V4p2_Price_BAO_FieldValue::deleteValues($id);
530
531 // reorder the weight before delete
532 $fieldValues = array('price_set_id' => $field->price_set_id);
533
534 CRM_Utils_Weight::delWeight('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field', $field->id, $fieldValues);
535
536 // now delete the field
537 return $field->delete();
538 }
539
540 return NULL;
541 }
542
543 /**
544 * @return array
545 */
546 public static function &htmlTypes() {
547 static $htmlTypes = NULL;
548 if (!$htmlTypes) {
549 $htmlTypes = array(
550 'Text' => ts('Text / Numeric Quantity'),
551 'Select' => ts('Select'),
552 'Radio' => ts('Radio'),
553 'CheckBox' => ts('CheckBox'),
554 );
555 }
556 return $htmlTypes;
557 }
558
559 /**
560 * Validate the priceset.
561 *
562 * @param int $priceSetId
563 * @param array $fields
564 * @param array $error
565 */
566 public static function priceSetValidation($priceSetId, $fields, &$error) {
567 // check for at least one positive
568 // amount price field should be selected.
569 $priceField = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field();
570 $priceField->price_set_id = $priceSetId;
571 $priceField->find();
572
573 $priceFields = array();
574
575 while ($priceField->fetch()) {
576 $key = "price_{$priceField->id}";
577 if (!empty($fields[$key])) {
578 $priceFields[$priceField->id] = $fields[$key];
579 }
580 }
581
582 if (!empty($priceFields)) {
583 // we should has to have positive amount.
584 $sql = "
585 SELECT id, html_type
586 FROM civicrm_price_field
587 WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
588 $fieldDAO = CRM_Core_DAO::executeQuery($sql);
589 $htmlTypes = array();
590 while ($fieldDAO->fetch()) {
591 $htmlTypes[$fieldDAO->id] = $fieldDAO->html_type;
592 }
593
594 $selectedAmounts = array();
595
596 foreach ($htmlTypes as $fieldId => $type) {
597 $options = array();
598 CRM_Upgrade_Snapshot_V4p2_Price_BAO_FieldValue::getValues($fieldId, $options);
599
600 if (empty($options)) {
601
602 continue;
603
604 }
605
606 if ($type == 'Text') {
607 foreach ($options as $opId => $option) {
608 $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount'];
609 break;
610 }
611 }
612 elseif (is_array($fields["price_{$fieldId}"])) {
613 foreach (array_keys($fields["price_{$fieldId}"]) as $opId) {
614 $selectedAmounts[$opId] = $options[$opId]['amount'];
615 }
616 }
617 elseif (in_array($fields["price_{$fieldId}"], array_keys($options))) {
618 $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount'];
619 }
620 }
621
622 list($componentName) = explode(':', $fields['_qf_default']);
623 // now we have all selected amount in hand.
624 $totalAmount = array_sum($selectedAmounts);
625 if ($totalAmount < 0) {
626 $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', array(1 => $componentName));
627 }
628 }
629 else {
630 $error['_qf_default'] = ts("Please select at least one option from price set.");
631 }
632 }
633
634 }