3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2018
35 * Business objects for managing price fields.
37 class CRM_Upgrade_Snapshot_V4p2_Price_BAO_Field
extends CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field
{
42 * Takes an associative array and creates a price field object.
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
48 * @param array $params
49 * (reference ) an assoc array of name/value pairs.
51 * @return CRM_Upgrade_Snapshot_V4p2_Price_BAO_Field
53 public static function &add(&$params) {
54 $priceFieldBAO = new CRM_Upgrade_Snapshot_V4p2_Price_BAO_Field();
56 $priceFieldBAO->copyValues($params);
58 if ($id = CRM_Utils_Array
::value('id', $params)) {
59 $priceFieldBAO->id
= $id;
62 $priceFieldBAO->save();
63 return $priceFieldBAO;
67 * Takes an associative array and creates a price field object.
69 * This function is invoked from within the web form layer and also from the api layer
71 * @param array $params
72 * (reference) an assoc array of name/value pairs.
74 * @return CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field
76 public static function create(&$params) {
78 $transaction = new CRM_Core_Transaction();
80 $priceField = self
::add($params);
82 if (is_a($priceField, 'CRM_Core_Error')) {
83 $transaction->rollback();
87 $options = $optionsIds = array();
88 $maxIndex = CRM_Price_Form_Field
::NUM_OPTION
;
90 if ($priceField->html_type
== 'Text') {
93 $fieldValue = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_FieldValue();
94 $fieldValue->price_field_id
= $priceField->id
;
96 // update previous field values( if any )
97 if ($fieldValue->find(TRUE)) {
98 $optionsIds['id'] = $fieldValue->id
;
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;
111 if (!empty($params['default_option'])) {
112 $defaultArray[$params['default_option']] = 1;
116 for ($index = 1; $index <= $maxIndex; $index++
) {
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])
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],
134 'is_default' => CRM_Utils_Array
::value($params['option_weight'][$index], $defaultArray) ?
$defaultArray[$params['option_weight'][$index]] : 0,
137 if ($opIds = CRM_Utils_Array
::value('option_id', $params)) {
138 if ($opId = CRM_Utils_Array
::value($index, $opIds)) {
139 $optionsIds['id'] = $opId;
142 $optionsIds['id'] = NULL;
145 CRM_Upgrade_Snapshot_V4p2_Price_BAO_FieldValue
::create($options, $optionsIds);
149 $transaction->commit();
154 * Fetch object based on array of properties.
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.
161 * @return CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field
163 public static function retrieve(&$params, &$defaults) {
164 return CRM_Core_DAO
::commonRetrieve('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field', $params, $defaults);
168 * Update the is_active flag in the db.
171 * Id of the database record.
172 * @param bool $is_active
173 * Value we want to set the is_active field.
176 * true if we found and updated the object, else false
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);
183 * Get the field title.
191 public static function getTitle($id) {
192 return CRM_Core_DAO
::getFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field', $id, 'label');
196 * This function for building custom fields.
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
213 public static function addQuickFormElement(
220 $fieldOptions = NULL,
221 $freezeOptions = array()
224 $field = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field();
225 $field->id
= $fieldId;
226 if (!$field->find(TRUE)) {
227 /* FIXME: failure! */
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
;
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
;
242 if ($field->name
== 'contribution_amount') {
243 $qf->_contributionAmount
= 1;
246 if (isset($qf->_online
) && $qf->_online
) {
247 $useRequired = FALSE;
250 $customOption = $fieldOptions;
251 if (!is_array($customOption)) {
252 $customOption = CRM_Upgrade_Snapshot_V4p2_Price_BAO_Field
::getOptions($field->id
, $inactiveNeeded);
256 $valueFieldName = 'amount';
258 switch ($field->html_type
) {
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));
266 if (property_exists($qf, '_quickConfig') && $qf->_quickConfig
&& property_exists($qf, '_contributionAmount') && $qf->_contributionAmount
) {
267 $qf->assign('priceset', $elementName);
268 $extra = array('onclick' => 'useAmountOther();');
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');
276 elseif (!empty($fieldOptions[$optionKey]['label'])) {
277 $label = $fieldOptions[$optionKey]['label'];
280 if ($field->is_display_amounts
) {
281 $label .= ' - ';
282 $label .= CRM_Utils_Money
::format(CRM_Utils_Array
::value($valueFieldName, $customOption[$optionKey]));
285 $element = &$qf->add('text', $elementName, $label,
288 'price' => json_encode(array($optionKey, $priceVal)),
292 $useRequired && $field->is_required
296 if (in_array($optionKey, $freezeOptions)) {
301 if (property_exists($qf, '_quickConfig') && $qf->_quickConfig
) {
302 $message = ts("Please enter a valid amount.");
306 $message = ts('%1 must be an integer (whole number).', array(1 => $label));
307 $type = "positiveInteger";
309 // integers will have numeric rule applied to them.
310 $qf->addRule($elementName, $message, $type);
316 if (property_exists($qf, '_quickConfig') && $qf->_quickConfig
&& property_exists($qf, '_contributionAmount') && $qf->_contributionAmount
) {
317 $qf->assign('contriPriceset', $elementName);
320 foreach ($customOption as $opId => $opt) {
321 if ($field->is_display_amounts
) {
322 $opt['label'] = !empty($opt['label']) ?
$opt['label'] . ' - ' : '';
323 $opt['label'] .= CRM_Utils_Money
::format($opt[$valueFieldName]);
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));
329 'price' => json_encode(array($elementName, $priceVal)),
330 'data-amount' => $opt[$valueFieldName],
331 'data-currency' => $currencyName,
333 if (property_exists($qf, '_quickConfig') && $qf->_quickConfig
&& $field->name
== 'contribution_amount') {
334 $extra +
= array('onclick' => 'clearAmountOther();');
336 elseif (property_exists($qf, '_quickConfig') && $qf->_quickConfig
&& $field->name
== 'membership_amount') {
338 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
339 'membership-type' => $opt['membership_type_id'],
341 $qf->assign('membershipFieldID', $field->id
);
343 $choice[$opId] = $qf->createElement('radio', NULL, '', $opt['label'], $opt['id'], $extra);
346 if (in_array($opId, $freezeOptions)) {
347 $choice[$opId]->freeze();
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',
354 'onclick' => 'clearAmountOther();',
359 if (!$field->is_required
) {
361 if (!empty($otherAmount['is_allow_other_amount']) && $field->name
== 'contribution_amount') {
362 $none = ts('Other Amount');
364 elseif (property_exists($qf, '_membershipBlock') && empty($qf->_membershipBlock
['is_required']) && $field->name
== 'membership_amount') {
365 $none = ts('No thank you');
368 $none = ts('-none-');
371 $choice[] = $qf->createElement('radio', NULL, '', $none, '0',
372 array('price' => json_encode(array($elementName, "0")))
376 $element = &$qf->addGroup($choice, $elementName, $label);
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;
383 if ($useRequired && $field->is_required
) {
384 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
389 $selectOption = $allowedOptions = $priceVal = array();
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));
396 if ($field->is_display_amounts
) {
397 $opt['label'] .= ' - ';
398 $opt['label'] .= CRM_Utils_Money
::format($opt[$valueFieldName]);
400 $selectOption[$opt['id']] = $opt['label'];
402 if (!in_array($opt['id'], $freezeOptions)) {
403 $allowedOptions[] = $opt['id'];
406 $element = &$qf->add('select', $elementName, $label,
407 array('' => ts('- select -')) +
$selectOption,
408 $useRequired && $field->is_required
,
409 array('price' => json_encode($priceVal))
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) . "/");
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));
427 if ($field->is_display_amounts
) {
428 $opt['label'] .= ' - ';
429 $opt['label'] .= CRM_Utils_Money
::format($opt[$valueFieldName]);
431 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
433 'price' => json_encode(array($opt['id'], $priceVal)),
434 'data-amount' => $opt[$valueFieldName],
435 'data-currency' => $currencyName,
440 if (in_array($opId, $freezeOptions)) {
441 $check[$opId]->freeze();
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');
450 if (isset($qf->_online
) && $qf->_online
) {
456 * Retrieve a list of options for the specified field.
458 * @param int $fieldId
460 * @param bool $inactiveNeeded
461 * Include inactive options.
463 * Ignore stored values\.
468 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE) {
469 static $options = array();
471 if ($reset ||
empty($options[$fieldId])) {
473 CRM_Upgrade_Snapshot_V4p2_Price_BAO_FieldValue
::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
474 $options[$fieldId] = $values;
477 return $options[$fieldId];
481 * @param $optionLabel
486 public static function getOptionId($optionLabel, $fid) {
487 if (!$optionLabel ||
!$fid) {
491 $optionGroupName = "civicrm_price_field.amount.{$fid}";
495 option_value.id as id
497 civicrm_option_value option_value,
498 civicrm_option_group option_group
500 option_group.name = %1
501 AND option_group.id = option_value.option_group_id
502 AND option_value.label = %2";
504 $dao = CRM_Core_DAO
::executeQuery($query, array(
505 1 => array($optionGroupName, 'String'),
506 2 => array($optionLabel, 'String'),
509 while ($dao->fetch()) {
515 * Delete the price set field.
523 public static function deleteField($id) {
524 $field = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field();
527 if ($field->find(TRUE)) {
528 // delete the options for this field
529 CRM_Upgrade_Snapshot_V4p2_Price_BAO_FieldValue
::deleteValues($id);
531 // reorder the weight before delete
532 $fieldValues = array('price_set_id' => $field->price_set_id
);
534 CRM_Utils_Weight
::delWeight('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field', $field->id
, $fieldValues);
536 // now delete the field
537 return $field->delete();
546 public static function &htmlTypes() {
547 static $htmlTypes = NULL;
550 'Text' => ts('Text / Numeric Quantity'),
551 'Select' => ts('Select'),
552 'Radio' => ts('Radio'),
553 'CheckBox' => ts('CheckBox'),
560 * Validate the priceset.
562 * @param int $priceSetId
563 * @param array $fields
564 * @param array $error
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;
573 $priceFields = array();
575 while ($priceField->fetch()) {
576 $key = "price_{$priceField->id}";
577 if (!empty($fields[$key])) {
578 $priceFields[$priceField->id
] = $fields[$key];
582 if (!empty($priceFields)) {
583 // we should has to have positive amount.
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
;
594 $selectedAmounts = array();
596 foreach ($htmlTypes as $fieldId => $type) {
598 CRM_Upgrade_Snapshot_V4p2_Price_BAO_FieldValue
::getValues($fieldId, $options);
600 if (empty($options)) {
606 if ($type == 'Text') {
607 foreach ($options as $opId => $option) {
608 $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount'];
612 elseif (is_array($fields["price_{$fieldId}"])) {
613 foreach (array_keys($fields["price_{$fieldId}"]) as $opId) {
614 $selectedAmounts[$opId] = $options[$opId]['amount'];
617 elseif (in_array($fields["price_{$fieldId}"], array_keys($options))) {
618 $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount'];
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));
630 $error['_qf_default'] = ts("Please select at least one option from price set.");