3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Business object for managing price sets.
22 class CRM_Price_BAO_PriceSet
extends CRM_Price_DAO_PriceSet
{
25 * Static field for default price set details.
29 public static $_defaultPriceSet = NULL;
32 * Takes an associative array and creates a price set object.
34 * @param array $params
35 * (reference) an assoc array of name/value pairs.
37 * @return CRM_Price_DAO_PriceSet
39 public static function create(&$params) {
40 $hook = empty($params['id']) ?
'create' : 'edit';
41 CRM_Utils_Hook
::pre($hook, 'PriceSet', CRM_Utils_Array
::value('id', $params), $params);
43 if (empty($params['id']) && empty($params['name'])) {
44 $params['name'] = CRM_Utils_String
::munge($params['title'], '_', 242);
47 $validatePriceSet = TRUE;
48 if (!empty($params['extends']) && is_array($params['extends'])) {
49 if (!array_key_exists(CRM_Core_Component
::getComponentID('CiviEvent'), $params['extends'])
50 ||
!array_key_exists(CRM_Core_Component
::getComponentID('CiviMember'), $params['extends'])
52 $validatePriceSet = FALSE;
54 $params['extends'] = CRM_Utils_Array
::implodePadded($params['extends']);
57 $priceSetID = $params['id'] ??
NULL;
59 $priceSetBAO = new CRM_Price_BAO_PriceSet();
60 $priceSetBAO->copyValues($params);
61 if (self
::eventPriceSetDomainID()) {
62 $priceSetBAO->domain_id
= CRM_Core_Config
::domainID();
66 CRM_Utils_Hook
::post($hook, 'PriceSet', $priceSetBAO->id
, $priceSetBAO);
67 unset(\Civi
::$statics['CRM_Core_PseudoConstant']);
72 * Retrieve DB object and copy to defaults array.
74 * @param array $params
75 * Array of criteria values.
76 * @param array $defaults
77 * Array to be populated with found values.
80 * The DAO object, if found.
84 public static function retrieve($params, &$defaults) {
85 return self
::commonRetrieve(self
::class, $params, $defaults);
89 * Update the is_active flag in the db.
92 * Id of the database record.
96 * true if we found and updated the object, else false
98 public static function setIsActive($id, $isActive) {
99 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
103 * Calculate the default price set id
104 * assigned to the contribution/membership etc
106 * @param string $entity
112 public static function getDefaultPriceSet($entity = 'contribution') {
113 if (isset(\Civi
::$statics[__CLASS__
][$entity])) {
114 return \Civi
::$statics[__CLASS__
][$entity];
116 $priceSetName = ($entity === 'membership') ?
'default_membership_type_amount' : 'default_contribution_amount';
119 SELECT ps.id AS setID, pfv.price_field_id AS priceFieldID, pfv.id AS priceFieldValueID, pfv.name, pfv.label, pfv.membership_type_id, pfv.amount, pfv.financial_type_id
120 FROM civicrm_price_set ps
121 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
122 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
123 WHERE ps.name = '{$priceSetName}'
126 $dao = CRM_Core_DAO
::executeQuery($sql);
127 while ($dao->fetch()) {
128 \Civi
::$statics[__CLASS__
][$entity][$dao->priceFieldValueID
] = [
129 'setID' => $dao->setID
,
130 'priceFieldID' => $dao->priceFieldID
,
131 'name' => $dao->name
,
132 'label' => $dao->label
,
133 'priceFieldValueID' => $dao->priceFieldValueID
,
134 'membership_type_id' => $dao->membership_type_id
,
135 'amount' => $dao->amount
,
136 'financial_type_id' => $dao->financial_type_id
,
140 return \Civi
::$statics[__CLASS__
][$entity];
144 * Get the price set title.
153 public static function getTitle($id) {
154 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
158 * Return a list of all forms which use this price set.
162 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
166 public static function getUsedBy($id, $simpleReturn = FALSE) {
168 $forms = self
::getFormsUsingPriceSet($id);
169 $tables = array_keys($forms);
170 // @todo - this is really clumsy overloading the signature like this. Instead
171 // move towards having a function that does not call reformatUsedByFormsWithEntityData
172 // and call that when that data is not used.
173 if ($simpleReturn == 'table') {
176 // @todo - this is painfully slow in some cases.
179 SELECT cli.entity_table, cli.entity_id
180 FROM civicrm_line_item cli
181 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
182 WHERE cpf.price_set_id = %1";
183 $params = [1 => [$id, 'Integer']];
184 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
185 while ($crmFormDAO->fetch()) {
186 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
187 $tables[] = $crmFormDAO->entity_table
;
193 // @todo - this is really clumsy overloading the signature like this. See above.
194 if ($simpleReturn == 'entity') {
197 $usedBy = self
::reformatUsedByFormsWithEntityData($forms, $usedBy);
203 * Delete the price set, including the fields.
209 * false if fields exist for this set, true if the
210 * set could be deleted
213 public static function deleteSet($id) {
214 // delete price fields
215 $priceField = new CRM_Price_DAO_PriceField();
216 $priceField->price_set_id
= $id;
218 while ($priceField->fetch()) {
219 // delete options first
220 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
223 $set = new CRM_Price_DAO_PriceSet();
225 return $set->delete();
229 * Link the price set with the specified table and id.
231 * @param string $entityTable
232 * @param int $entityId
233 * @param int $priceSetId
237 public static function addTo($entityTable, $entityId, $priceSetId) {
238 // verify that the price set exists
239 $dao = new CRM_Price_DAO_PriceSet();
240 $dao->id
= $priceSetId;
246 $dao = new CRM_Price_DAO_PriceSetEntity();
247 // find if this already exists
248 $dao->entity_id
= $entityId;
249 $dao->entity_table
= $entityTable;
252 // add or update price_set_id
253 $dao->price_set_id
= $priceSetId;
258 * Delete price set for the given entity and id.
260 * @param string $entityTable
261 * @param int $entityId
265 public static function removeFrom($entityTable, $entityId) {
266 $dao = new CRM_Price_DAO_PriceSetEntity();
267 $dao->entity_table
= $entityTable;
268 $dao->entity_id
= $entityId;
269 return $dao->delete();
273 * Find a price_set_id associated with the given table, id and usedFor
274 * Used For value for events:1, contribution:2, membership:3
276 * @param string $entityTable
277 * @param int $entityId
278 * @param int $usedFor
279 * ( price set that extends/used for particular component ).
281 * @param null $isQuickConfig
282 * @param null $setName
285 * price_set_id, or false if none found
287 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
288 if (!$entityTable ||
!$entityId) {
292 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
293 FROM civicrm_price_set ps
294 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
295 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
296 if ($isQuickConfig) {
297 $sql .= ' AND ps.is_quick_config = 0 ';
300 1 => [$entityTable, 'String'],
301 2 => [$entityId, 'Integer'],
304 $sql .= " AND ps.extends LIKE '%%3%' ";
305 $params[3] = [$usedFor, 'Integer'];
308 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
310 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
311 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
315 * Find a price_set_id associated with the given option value or field ID.
317 * @param array $params
318 * (reference) an assoc array of name/value pairs.
319 * array may contain either option id or
323 * price set id on success, null otherwise
325 public static function getSetId(&$params) {
328 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
329 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
330 $fieldValue->id
= $oid;
331 if ($fieldValue->find(TRUE)) {
332 $fid = $fieldValue->price_field_id
;
336 $fid = $params['fid'] ??
NULL;
340 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
347 * Return an associative array of all price sets.
349 * @param bool $withInactive
350 * Whether or not to include inactive entries.
351 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
352 * @param string $column name of the column.
355 * associative array of id => name
357 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE, $column = 'title') {
360 DISTINCT ( price_set_id ) as id, s.{$column}
363 INNER JOIN civicrm_price_field f ON f.price_set_id = s.id
364 INNER JOIN civicrm_price_field_value v ON v.price_field_id = f.id
366 is_quick_config = 0 ";
368 if (!$withInactive) {
369 $query .= ' AND s.is_active = 1 ';
372 if (self
::eventPriceSetDomainID()) {
373 $query .= ' AND s.domain_id = ' . CRM_Core_Config
::domainID();
378 if ($extendComponentName) {
379 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
383 $query .= " AND s.extends LIKE '%$componentId%' ";
385 // Check permissioned financial types
386 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialType, CRM_Core_Action
::ADD
);
387 if ($financialType) {
388 $types = implode(',', array_keys($financialType));
389 $query .= ' AND s.financial_type_id IN (' . $types . ') AND v.financial_type_id IN (' . $types . ') ';
392 // Do not display any price sets
395 $query .= " GROUP BY s.id";
396 $dao = CRM_Core_DAO
::executeQuery($query);
397 while ($dao->fetch()) {
398 $priceSets[$dao->id
] = $dao->$column;
404 * Get price set details.
406 * An array containing price set details (including price fields) is returned
410 * @param bool $required
411 * Appears to have no effect based on reading the code.
412 * @param bool $doNotIncludeExpiredFields
413 * Should only fields where today's date falls within the valid range be returned?
416 * Array consisting of field details
418 public static function getSetDetail($setID, $required = TRUE, $doNotIncludeExpiredFields = FALSE) {
431 'is_display_amounts',
440 if ($required == TRUE) {
441 $priceFields[] = 'is_required';
445 $select = 'SELECT ' . implode(',', $priceFields);
446 $from = ' FROM civicrm_price_field';
449 1 => [$setID, 'Integer'],
451 $currentTime = date('YmdHis');
453 WHERE price_set_id = %1
457 if ($doNotIncludeExpiredFields) {
459 AND ( active_on IS NULL OR active_on <= {$currentTime} )
460 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
464 $orderBy = ' ORDER BY weight';
466 $sql = $select . $from . $where . $dateSelect . $orderBy;
468 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
470 $isDefaultContributionPriceSet = FALSE;
471 if ('default_contribution_amount' == CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $setID)) {
472 $isDefaultContributionPriceSet = TRUE;
475 $visibility = CRM_Core_PseudoConstant
::visibility('name');
476 while ($dao->fetch()) {
479 $setTree[$setID]['fields'][$fieldID] = [];
480 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
482 foreach ($priceFields as $field) {
483 if ($field == 'id' ||
is_null($dao->$field)) {
487 if ($field == 'visibility_id') {
488 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
490 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
492 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE, FALSE, $isDefaultContributionPriceSet);
495 // also get the pre and post help from this price set
497 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config, min_amount
498 FROM civicrm_price_set
500 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
502 $setTree[$setID]['extends'] = $dao->extends;
503 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
504 $setTree[$setID]['help_pre'] = $dao->help_pre
;
505 $setTree[$setID]['help_post'] = $dao->help_post
;
506 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
507 $setTree[$setID]['min_amount'] = $dao->min_amount
;
513 * Get the Price Field ID.
515 * We call this function when more than one being present would represent an error
516 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
517 * @param array $priceSet
519 * @throws CRM_Core_Exception
522 public static function getOnlyPriceFieldID(array $priceSet) {
523 if (count($priceSet['fields']) > 1) {
524 throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
526 return (int) implode('_', array_keys($priceSet['fields']));
530 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
531 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
532 * @param array $priceSet
534 * @throws CRM_Core_Exception
537 public static function getOnlyPriceFieldValueID(array $priceSet) {
538 $priceFieldID = self
::getOnlyPriceFieldID($priceSet);
539 if (count($priceSet['fields'][$priceFieldID]['options']) > 1) {
540 throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
542 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
546 * Initiate price set such that various non-BAO things are set on the form.
548 * This function is not really a BAO function so the location is misleading.
550 * @param CRM_Core_Form $form
552 * @param string $entityTable
553 * @param bool $doNotIncludeExpiredFields
554 * @param int $priceSetId
557 public static function initSet(&$form, $entityTable = 'civicrm_event', $doNotIncludeExpiredFields = FALSE, $priceSetId = NULL) {
559 //check if price set is is_config
560 if (is_numeric($priceSetId)) {
561 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
562 $form->assign('quickConfig', 1);
567 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
568 $entityId = $entity = NULL;
570 switch ($entityTable) {
571 case 'civicrm_event':
572 $entity = 'participant';
573 if (in_array(CRM_Utils_System
::getClassName($form), ['CRM_Event_Form_Participant', 'CRM_Event_Form_Task_Register'])) {
574 $entityId = $form->_id
;
577 $entityId = $form->_participantId
;
581 case 'civicrm_contribution_page':
582 case 'civicrm_contribution':
583 $entity = 'contribution';
584 $entityId = $form->_id
;
588 if ($entityId && $entity) {
589 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
597 $form->_priceSetId
= $priceSetId;
598 $priceSet = self
::getSetDetail($priceSetId, $required, $doNotIncludeExpiredFields);
599 $form->_priceSet
= $priceSet[$priceSetId] ??
NULL;
600 $form->_values
['fee'] = $form->_priceSet
['fields'] ??
NULL;
602 //get the price set fields participant count.
603 if ($entityTable == 'civicrm_event') {
604 //get option count info.
605 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
606 if ($form->_priceSet
['optionsCountTotal']) {
607 $optionsCountDetails = [];
608 if (!empty($form->_priceSet
['fields'])) {
609 foreach ($form->_priceSet
['fields'] as $field) {
610 foreach ($field['options'] as $option) {
611 $count = CRM_Utils_Array
::value('count', $option, 0);
612 $optionsCountDetails['fields'][$field['id']]['options'][$option['id']] = $count;
616 $form->_priceSet
['optionsCountDetails'] = $optionsCountDetails;
619 //get option max value info.
620 $optionsMaxValueTotal = 0;
621 $optionsMaxValueDetails = [];
623 if (!empty($form->_priceSet
['fields'])) {
624 foreach ($form->_priceSet
['fields'] as $field) {
625 foreach ($field['options'] as $option) {
626 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
627 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
628 $optionsMaxValueTotal +
= $maxVal;
633 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
634 if ($optionsMaxValueTotal) {
635 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
638 $form->set('priceSetId', $form->_priceSetId
);
639 $form->set('priceSet', $form->_priceSet
);
644 * Get line item purchase information.
646 * This function takes the input parameters and interprets out of it what has been purchased.
649 * This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
650 * And, it would make sense to introduce caching into that function and call it from here rather than
651 * require the $fields array which is passed from pillar to post around the form in order to pass it in here.
652 * @param array $params
653 * Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
655 * Line item array to be altered.
656 * @param int $priceSetID
658 * @todo $priceSetID is a pseudoparam for permit override - we should stop passing it where we
659 * don't specifically need it & find a better way where we do.
661 public static function processAmount($fields, &$params, &$lineItem, $priceSetID = NULL) {
663 $totalPrice = $totalTax = 0;
664 foreach ($fields as $id => $field) {
665 if (empty($params["price_{$id}"]) ||
666 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
668 // skip if nothing was submitted for this field
672 [$params, $lineItem] = self
::getLine($params, $lineItem, $priceSetID, $field, $id);
676 $totalParticipant = 0;
677 if (is_array($lineItem)) {
678 foreach ($lineItem as $values) {
679 $totalPrice +
= $values['line_total'] +
$values['tax_amount'];
680 $totalTax +
= $values['tax_amount'];
681 $totalParticipant +
= $values['participant_count'];
682 // This is a bit nasty. The logic of 'quick config' was because price set configuration was
683 // (and still is) too difficult to replace the 'quick config' price set configuration on the contribution
686 // However, because the quick config concept existed all sorts of logic was hung off it
687 // and function behaviour sometimes depends on whether 'price set' is set - although actually it
688 // is always set at the functional level. In this case we are dealing with the default 'quick config'
689 // price set having a label of 'Contribution Amount' which could wind up creating a 'funny looking' label.
690 // The correct answer is probably for it to have an empty label in the DB - the label is never shown so it is a
693 // But, in the interests of being careful when capacity is low - avoiding the known default value
695 // Crucially a test has been added so a better solution can be implemented later with some comfort.
696 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
697 if ($values['label'] !== ts('Contribution Amount')) {
698 $amount_level[] = $values['label'] . ' - ' . (float) $values['qty'];
703 $displayParticipantCount = '';
704 if ($totalParticipant > 0) {
705 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
707 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
708 if (!empty($amount_level)) {
709 $params['amount_level'] = CRM_Utils_Array
::implodePadded($amount_level);
710 if (!empty($displayParticipantCount)) {
711 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
715 $params['amount'] = $totalPrice;
716 $params['tax_amount'] = $totalTax;
720 * Get the text to record for amount level.
722 * @param array $params
723 * Submitted parameters
724 * - priceSetId is required to be set in the calling function
725 * (we don't e-notice check it to enforce that - all payments DO have a price set - even if it is the
726 * default one & this function asks that be set if it is the case).
729 * Text for civicrm_contribution.amount_level field.
731 public static function getAmountLevelText($params): string {
732 $priceSetID = $params['priceSetId'];
733 $priceFieldSelection = self
::filterPriceFieldsFromParams($priceSetID, $params);
734 $priceFieldMetadata = self
::getCachedPriceSetDetail($priceSetID);
735 $displayParticipantCount = NULL;
738 foreach ($priceFieldMetadata['fields'] as $field) {
739 if (!empty($priceFieldSelection[$field['id']])) {
740 // We deliberately & specifically exclude contribution amount as it has a specific meaning.
741 // ie. it represents the default price field for a contribution. Another approach would be not
742 // to give it a label if we don't want it to show.
743 if ($field['label'] !== ts('Contribution Amount')) {
744 $amount_level[] = $field['label'] . ($field['is_enter_qty'] ?
' - ' . (float) $params['price_' . $field['id']] : '');
748 return CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . CRM_Core_DAO
::VALUE_SEPARATOR
;
752 * Get the fields relevant to the price field from the parameters.
754 * E.g we are looking for price_5 => 7 out of a big array of input parameters.
756 * @param int $priceSetID
757 * @param array $params
760 * Price fields found in the params array
762 public static function filterPriceFieldsFromParams($priceSetID, $params) {
763 $priceSet = self
::getCachedPriceSetDetail($priceSetID);
765 foreach ($priceSet['fields'] as $field) {
766 if (!empty($params['price_' . $field['id']])) {
767 $return[$field['id']] = $params['price_' . $field['id']];
774 * Wrapper for getSetDetail with caching.
776 * We seem to be passing this array around in a painful way - presumably to avoid the hit
777 * of loading it - so lets make it callable with caching.
779 * Why not just add caching to the other function? We could do - it just seemed a bit unclear the best caching pattern
780 * & the function was already pretty fugly. Also, I feel like we need to migrate the interaction with price-sets into
781 * a more granular interaction - ie. retrieve specific data using specific functions on this class & have the form
782 * think less about the price sets.
784 * @param int $priceSetID
788 public static function getCachedPriceSetDetail($priceSetID) {
789 $cacheKey = __CLASS__
. __FUNCTION__
. '_' . $priceSetID;
790 $cache = CRM_Utils_Cache
::singleton();
791 $values = $cache->get($cacheKey);
792 if (empty($values)) {
793 $data = self
::getSetDetail($priceSetID);
794 $values = $data[$priceSetID];
795 $cache->set($cacheKey, $values);
801 * Build the price set form.
803 * @param CRM_Core_Form $form
807 public static function buildPriceSet(&$form) {
808 $priceSetId = $form->get('priceSetId');
813 $validFieldsOnly = TRUE;
814 $className = CRM_Utils_System
::getClassName($form);
815 if (in_array($className, [
816 'CRM_Contribute_Form_Contribution',
817 'CRM_Member_Form_Membership',
819 $validFieldsOnly = FALSE;
822 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
823 $form->_priceSet
= $priceSet[$priceSetId] ??
NULL;
824 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
825 $form->_quickConfig
= $quickConfig = 0;
826 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
830 $form->assign('quickConfig', $quickConfig);
831 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
832 $form->_quickConfig
= $quickConfig;
835 // Mark which field should have the auto-renew checkbox, if any. CRM-18305
836 if (!empty($form->_membershipTypeValues
) && is_array($form->_membershipTypeValues
)) {
837 $autoRenewMembershipTypes = [];
838 foreach ($form->_membershipTypeValues
as $membershipTypeValue) {
839 if ($membershipTypeValue['auto_renew']) {
840 $autoRenewMembershipTypes[] = $membershipTypeValue['id'];
843 foreach ($form->_priceSet
['fields'] as $field) {
844 if (array_key_exists('options', $field) && is_array($field['options'])) {
845 foreach ($field['options'] as $option) {
846 if (!empty($option['membership_type_id'])) {
847 if (in_array($option['membership_type_id'], $autoRenewMembershipTypes)) {
848 $form->_priceSet
['auto_renew_membership_field'] = $field['id'];
849 // Only one field can offer auto_renew memberships, so break here.
857 $form->_priceSet
['id'] = $form->_priceSet
['id'] ??
$priceSetId;
858 $form->assign('priceSet', $form->_priceSet
);
860 $component = 'contribution';
861 if ($className == 'CRM_Member_Form_Membership') {
862 $component = 'membership';
865 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
866 $feeBlock = &$form->_values
['fee'];
867 if (!empty($form->_useForMember
)) {
868 $component = 'membership';
872 $feeBlock = &$form->_priceSet
['fields'];
875 // Call the buildAmount hook.
876 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
878 self
::addPriceFieldsToForm($form, $feeBlock, $validFieldsOnly, $className, $validPriceFieldIds);
882 * Check the current Membership having end date null.
884 * @param array $options
886 * Probably actually contact ID.
890 public static function checkCurrentMembership(&$options, $userid) {
891 if (!$userid ||
empty($options)) {
894 static $_contact_memberships = [];
895 $checkLifetime = FALSE;
896 foreach ($options as $key => $value) {
897 if (!empty($value['membership_type_id'])) {
898 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
899 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
901 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
902 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
903 unset($options[$key]);
904 $checkLifetime = TRUE;
908 if ($checkLifetime) {
917 * Set daefult the price set fields.
919 * @param CRM_Core_Form $form
924 public static function setDefaultPriceSet(&$form, &$defaults) {
925 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
929 foreach ($form->_priceSet
['fields'] as $val) {
930 foreach ($val['options'] as $keys => $values) {
931 // build price field index which is passed via URL
932 // url format will be appended by "&price_5=11"
933 $priceFieldName = 'price_' . $values['price_field_id'];
934 $priceFieldValue = self
::getPriceFieldValueFromURL($form, $priceFieldName);
935 if (!empty($priceFieldValue)) {
936 self
::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $defaults);
937 // break here to prevent overwriting of default due to 'is_default'
938 // option configuration. The value sent via URL get's higher priority.
941 elseif ($values['is_default']) {
942 self
::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $defaults);
950 * Get the value of price field if passed via url
952 * @param string $priceFieldName
953 * @param string $priceFieldValue
954 * @param string $priceFieldType
955 * @param array $defaults
959 public static function setDefaultPriceSetField($priceFieldName, $priceFieldValue, $priceFieldType, &$defaults) {
960 if ($priceFieldType == 'CheckBox') {
961 $defaults[$priceFieldName][$priceFieldValue] = 1;
964 $defaults[$priceFieldName] = $priceFieldValue;
969 * Get the value of price field if passed via url
971 * @param CRM_Core_Form $form
972 * @param string $priceFieldName
974 * @return mixed $priceFieldValue
976 public static function getPriceFieldValueFromURL(&$form, $priceFieldName) {
977 $priceFieldValue = CRM_Utils_Request
::retrieve($priceFieldName, 'String', $form, FALSE, NULL, 'GET');
978 if (!empty($priceFieldValue)) {
979 return $priceFieldValue;
984 * Supports event create function by setting up required price sets, not tested but expect
985 * it will work for contribution page
986 * @param array $params
987 * As passed to api/bao create fn.
988 * @param CRM_Core_DAO $entity
989 * Object for given entity.
990 * @param string $entityName
991 * Name of entity - e.g event.
993 public static function setPriceSets(&$params, $entity, $entityName) {
994 if (empty($params['price_set_id']) ||
!is_array($params['price_set_id'])) {
997 // CRM-14069 note that we may as well start by assuming more than one.
998 // currently the form does not pass in as an array & will be skipped
999 // test is passing in as an array but I feel the api should have a metadata that allows
1000 // transform of single to array - seems good for managing transitions - in which case all api
1001 // calls that set price_set_id will hit this
1002 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1003 // all separated values, strings, json half-separated values (in participant we hit this)
1004 // to be converted to json @ api layer
1005 $pse = new CRM_Price_DAO_PriceSetEntity();
1006 $pse->entity_table
= 'civicrm_' . $entityName;
1007 $pse->entity_id
= $entity->id
;
1008 while ($pse->fetch()) {
1009 if (!in_array($pse->price_set_id
, $params['price_set_id'])) {
1010 // note an even more aggressive form of this deletion currently happens in event form
1011 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1012 // on the participant record
1013 if (CRM_Price_BAO_PriceSet
::removeFrom('civicrm_' . $entityName, $entity->id
)) {
1014 CRM_Core_BAO_Discount
::del($entity->id
, 'civicrm_' . $entityName);
1018 foreach ($params['price_set_id'] as $priceSetID) {
1019 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $entityName, $entity->id
, $priceSetID);
1020 //@todo - how should we do this - copied from form
1021 //if (!empty($params['price_field_id'])) {
1022 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1023 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1029 * Get field ids of a price set.
1035 * Array of the field ids
1038 public static function getFieldIds($id) {
1039 $priceField = new CRM_Price_DAO_PriceField();
1040 $priceField->price_set_id
= $id;
1041 $priceField->find();
1042 while ($priceField->fetch()) {
1043 $var[] = $priceField->id
;
1049 * Copy a price set, including all the fields
1052 * The price set id to copy.
1054 * @return CRM_Price_DAO_PriceSet
1056 public static function copy($id) {
1057 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1058 $priceSet = civicrm_api3('PriceSet', 'getsingle', ['id' => $id]);
1060 $newTitle = preg_replace('/\[Copy id \d+\]$/', "", $priceSet['title']);
1061 $title = ts('[Copy id %1]', [1 => $maxId +
1]);
1064 'title' => trim($newTitle) . ' ' . $title,
1065 'name' => substr($priceSet['name'], 0, 20) . 'price_set_' . ($maxId +
1),
1069 $copy = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1075 //copying all the blocks pertaining to the price set
1076 $copyPriceField = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1077 ['price_set_id' => $id],
1078 ['price_set_id' => $copy->id
]
1080 if (!empty($copyPriceField)) {
1081 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1083 //copy option group and values
1084 foreach ($price as $originalId => $copyId) {
1085 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1086 ['price_field_id' => $originalId],
1087 ['price_field_id' => $copyId]
1093 CRM_Utils_Hook
::copy('Set', $copy);
1094 unset(\Civi
::$statics['CRM_Core_PseudoConstant']);
1099 * check price set permission.
1105 * @throws \CRM_Core_Exception
1107 public static function checkPermission($sid) {
1108 if ($sid && self
::eventPriceSetDomainID()) {
1109 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1110 if (CRM_Core_Config
::domainID() != $domain_id) {
1111 CRM_Core_Error
::statusBounce(ts('You do not have permission to access this page.'));
1118 * Get the sum of participant count
1119 * for all fields of given price set.
1124 * @param bool $onlyActive
1126 * @return int|null|string
1128 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1136 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1139 static $pricesetFieldCount = [];
1140 if (!isset($pricesetFieldCount[$sid])) {
1142 SELECT sum(value.count) as totalCount
1143 FROM civicrm_price_field_value value
1144 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1145 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1149 $count = CRM_Core_DAO
::singleValueQuery($sql, [1 => [$sid, 'Positive']]);
1150 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1153 return $pricesetFieldCount[$sid];
1157 * Return a count of priceFieldValueIDs that are memberships by organisation and membership type
1159 * @param string $priceFieldValueIDs
1160 * Comma separated string of priceFieldValue IDs
1163 * Returns an array of counts by membership organisation
1165 public static function getMembershipCount($priceFieldValueIDs) {
1167 SELECT count( pfv.id ) AS count, mt.member_of_contact_id AS id
1168 FROM civicrm_price_field_value pfv
1169 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1170 WHERE pfv.id IN ( $priceFieldValueIDs )
1171 GROUP BY mt.member_of_contact_id ";
1173 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1176 while ($crmDAO->fetch()) {
1177 $count[$crmDAO->id
] = $crmDAO->count
;
1184 * Check if auto renew option should be shown.
1186 * The auto-renew option should be visible if membership types associated with all the fields has
1187 * been set for auto-renew option.
1189 * Auto renew checkbox should be frozen if for all the membership type auto renew is required
1191 * @param int $priceSetId
1195 * $autoRenewOption ( 0:hide, 1:optional 2:required )
1197 public static function checkAutoRenewForPriceSet($priceSetId) {
1198 // auto-renew option should be visible if membership types associated with all the fields has
1199 // been set for auto-renew option
1200 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1202 // get the membership type auto renew option and check if required or optional
1203 $query = 'SELECT DISTINCT mt.auto_renew, mt.duration_interval, mt.duration_unit,
1204 pf.html_type, pf.id as price_field_id
1205 FROM civicrm_price_field_value pfv
1206 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1207 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1208 WHERE pf.price_set_id = %1
1209 AND pf.is_active = 1
1210 AND pfv.is_active = 1
1211 ORDER BY price_field_id';
1213 $params = [1 => [$priceSetId, 'Integer']];
1215 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1217 //CRM-18050: Check count of price set fields which has been set with auto-renew option.
1218 //If price set field is already present with auto-renew option then, it will restrict for adding another price set field with auto-renew option.
1223 $autoRenewOption = 2;
1225 while ($dao->fetch()) {
1226 if (!$dao->auto_renew
) {
1227 // If any one can't be renewed none can.
1230 if ($dao->auto_renew
== 1) {
1231 $autoRenewOption = 1;
1234 if ($dao->html_type
== 'Checkbox' && !in_array($dao->duration_interval
. $dao->duration_unit
, $priceFields[$dao->price_field_id
])) {
1235 // Checkbox fields cannot support auto-renew if they have more than one duration configuration
1236 // as more than one can be selected. Radio and select are either-or so they can have more than one duration.
1239 $priceFields[$dao->price_field_id
][] = $dao->duration_interval
. $dao->duration_unit
;
1240 foreach ($priceFields as $priceFieldID => $durations) {
1241 if ($priceFieldID != $dao->price_field_id
&& !in_array($dao->duration_interval
. $dao->duration_unit
, $durations)) {
1242 // Another price field has a duration configuration that differs so we can't offer auto-renew.
1248 return $autoRenewOption;
1252 * Retrieve auto renew frequency and interval.
1254 * @param int $priceSetId
1258 * associate array of frequency interval and unit
1260 // Ruben Added `, $priceFieldValueIds` here.
1261 public static function getRecurDetails($priceSetId, $priceFieldValueIds) {
1262 $query = 'SELECT mt.duration_interval, mt.duration_unit
1263 FROM civicrm_price_field_value pfv
1264 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1265 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1266 WHERE pf.price_set_id = %1 AND pfv.id = '
1267 . $priceFieldValueIds . ' LIMIT 1';
1269 $params = [1 => [$priceSetId, 'Integer']];
1270 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1272 return [$dao->duration_interval
, $dao->duration_unit
];
1278 public static function eventPriceSetDomainID() {
1279 return Civi
::settings()->get('event_price_set_domain_id');
1283 * Update the is_quick_config flag in the db.
1286 * Id of the database record.
1287 * @param bool $isQuickConfig we want to set the is_quick_config field.
1288 * Value we want to set the is_quick_config field.
1291 * true if we found and updated the object, else false
1293 public static function setIsQuickConfig($id, $isQuickConfig) {
1294 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1298 * Check if price set id provides option for user to select both auto-renew and non-auto-renew memberships
1304 public static function isMembershipPriceSetContainsMixOfRenewNonRenew($id) {
1305 $membershipTypes = self
::getMembershipTypesFromPriceSet($id);
1306 if (!empty($membershipTypes['autorenew']) && !empty($membershipTypes['non_renew'])) {
1313 * Get an array of the membership types in a price set.
1318 * Membership types in the price set
1320 public static function getMembershipTypesFromPriceSet($id) {
1322 = "SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1323 FROM civicrm_price_field_value pfv
1324 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1325 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1326 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1330 $params = [1 => [$id, 'Integer']];
1331 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1333 $membershipTypes = [
1336 'autorenew_required' => [],
1337 'autorenew_optional' => [],
1339 while ($dao->fetch()) {
1340 if (empty($dao->membership_type_id
)) {
1343 $membershipTypes['all'][] = $dao->membership_type_id
;
1344 if (!empty($dao->auto_renew
)) {
1345 $membershipTypes['autorenew'][] = $dao->membership_type_id
;
1346 if ($dao->auto_renew
== 2) {
1347 $membershipTypes['autorenew_required'][] = $dao->membership_type_id
;
1350 $membershipTypes['autorenew_optional'][] = $dao->membership_type_id
;
1354 $membershipTypes['non_renew'][] = $dao->membership_type_id
;
1357 return $membershipTypes;
1361 * Copy priceSet when event/contibution page is copied
1363 * @param string $baoName
1366 * Old event/contribution page id.
1368 * Newly created event/contribution page id.
1370 public static function copyPriceSet($baoName, $id, $newId) {
1371 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1373 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1374 if ($isQuickConfig) {
1375 $copyPriceSet = CRM_Price_BAO_PriceSet
::copy($priceSetId);
1376 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1379 $copyPriceSet = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1382 'entity_table' => $baoName,
1384 ['entity_id' => $newId]
1387 // copy event discount
1388 if ($baoName == 'civicrm_event') {
1389 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1390 foreach ($discount as $discountId => $setId) {
1392 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1394 CRM_Core_DAO
::copyGeneric(
1395 'CRM_Core_DAO_Discount',
1397 'id' => $discountId,
1400 'entity_id' => $newId,
1401 'price_set_id' => $copyPriceSet->id
,
1410 * Function to set tax_amount and tax_rate in LineItem.
1412 * @param array $field
1413 * @param array $lineItem
1414 * @param int $optionValueId
1415 * @param float $totalTax
1419 public static function setLineItem($field, $lineItem, $optionValueId, &$totalTax) {
1420 // Here we round - i.e. after multiplying by quantity
1421 if ($field['html_type'] == 'Text') {
1422 $taxAmount = round($field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'], 2);
1425 $taxAmount = round($field['options'][$optionValueId]['tax_amount'], 2);
1427 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1428 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1429 $lineItem[$optionValueId]['tax_rate'] = $taxRate;
1430 $totalTax +
= $taxAmount;
1435 * Get the first price set value IDs from a parameters array.
1437 * In practice this is really used when we only expect one to exist.
1439 * @param array $params
1442 * Array of the ids of the price set values.
1444 public static function parseFirstPriceSetValueIDFromParams($params) {
1445 $priceSetValueIDs = self
::parsePriceSetValueIDsFromParams($params);
1446 return reset($priceSetValueIDs);
1450 * Get the price set value IDs from a set of parameters
1452 * @param array $params
1455 * Array of the ids of the price set values.
1457 public static function parsePriceSetValueIDsFromParams($params) {
1458 $priceSetParams = self
::parsePriceSetArrayFromParams($params);
1459 $priceSetValueIDs = [];
1460 foreach ($priceSetParams as $priceSetParam) {
1461 foreach (array_keys($priceSetParam) as $priceValueID) {
1462 $priceSetValueIDs[] = $priceValueID;
1465 return $priceSetValueIDs;
1469 * Get the price set value IDs from a set of parameters
1471 * @param array $params
1474 * Array of price fields filtered from the params.
1476 public static function parsePriceSetArrayFromParams($params) {
1477 $priceSetParams = [];
1478 foreach ($params as $field => $value) {
1479 $parts = explode('_', $field);
1480 if (count($parts) == 2 && $parts[0] == 'price' && is_numeric($parts[1]) && is_array($value)) {
1481 $priceSetParams[$field] = $value;
1484 return $priceSetParams;
1488 * Get non-deductible amount from price options
1490 * @param int $priceSetId
1491 * @param array $lineItem
1494 * calculated non-deductible amount.
1496 public static function getNonDeductibleAmountFromPriceSet($priceSetId, $lineItem) {
1497 $nonDeductibleAmount = 0;
1498 if (!empty($lineItem[$priceSetId])) {
1499 foreach ($lineItem[$priceSetId] as $options) {
1500 $nonDeductibleAmount +
= $options['non_deductible_amount'] * $options['qty'];
1504 return $nonDeductibleAmount;
1508 * Get an array of all forms using a given price set.
1513 * Pages using the price set, keyed by type. e.g
1515 * 'civicrm_contribution_page' => array(2,5,6),
1516 * 'civicrm_event' => array(5,6),
1517 * 'civicrm_event_template' => array(7),
1520 public static function getFormsUsingPriceSet($id) {
1523 SELECT entity_table, entity_id
1524 FROM civicrm_price_set_entity
1525 WHERE price_set_id = %1";
1526 $params = [1 => [$id, 'Integer']];
1527 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1529 while ($crmFormDAO->fetch()) {
1530 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
1536 * @param array $forms
1537 * Array of forms that use a price set keyed by entity. e.g
1539 * 'civicrm_contribution_page' => array(2,5,6),
1540 * 'civicrm_event' => array(5,6),
1541 * 'civicrm_event_template' => array(7),
1545 * Array of entities suppliemented with per entity information.
1547 * array('civicrm_event' => array(7 => array('title' => 'x'...))
1549 * @throws \Exception
1551 protected static function reformatUsedByFormsWithEntityData($forms) {
1553 foreach ($forms as $table => $entities) {
1555 case 'civicrm_event':
1556 $ids = implode(',', $entities);
1557 $queryString = "SELECT ce.id as id, ce.title as title, ce.is_public as isPublic, ce.start_date as startDate, ce.end_date as endDate, civicrm_option_value.label as eventType, ce.is_template as isTemplate, ce.template_title as templateTitle
1558 FROM civicrm_event ce
1559 LEFT JOIN civicrm_option_value ON
1560 ( ce.event_type_id = civicrm_option_value.value )
1561 LEFT JOIN civicrm_option_group ON
1562 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
1564 civicrm_option_group.name = 'event_type' AND
1567 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1568 while ($crmDAO->fetch()) {
1569 if ($crmDAO->isTemplate
) {
1570 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
1571 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
1572 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
1575 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
1576 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
1577 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
1578 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
1579 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
1584 case 'civicrm_contribution_page':
1585 $ids = implode(',', $entities);
1586 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
1587 FROM civicrm_contribution_page cp, civicrm_financial_type ct
1588 WHERE ct.id = cp.financial_type_id AND
1591 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1592 while ($crmDAO->fetch()) {
1593 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
1594 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
1595 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
1596 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
1600 case 'civicrm_contribution':
1601 case 'civicrm_membership':
1602 case 'civicrm_participant':
1603 $usedBy[$table] = 1;
1607 throw new CRM_Core_Exception("$table is not supported in PriceSet::usedBy()");
1615 * Get the relevant line item.
1617 * Note this is part of code being cleaned up / refactored & may change.
1619 * @param array $params
1620 * @param array $lineItem
1621 * @param int $priceSetID
1622 * @param array $field
1627 public static function getLine(&$params, &$lineItem, $priceSetID, $field, $id): array {
1629 switch ($field['html_type']) {
1631 $firstOption = reset($field['options']);
1632 $params["price_{$id}"] = [$firstOption['id'] => $params["price_{$id}"]];
1633 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
1634 $optionValueId = key($field['options']);
1636 if (CRM_Utils_Array
::value('name', $field['options'][$optionValueId]) === 'contribution_amount') {
1637 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
1638 if (array_key_exists($params['financial_type_id'], $taxRates)) {
1639 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
1640 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($field['options'][$optionValueId]['amount'], $field['options'][$optionValueId]['tax_rate']);
1641 $field['options'][$optionValueId]['tax_amount'] = round($taxAmount['tax_amount'], 2);
1644 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
1645 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
1650 //special case if user select -none-
1651 if ($params["price_{$id}"] <= 0) {
1654 $params["price_{$id}"] = [$params["price_{$id}"] => 1];
1655 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
1657 // CRM-18701 Sometimes the amount in the price set is overridden by the amount on the form.
1658 // This is notably the case with memberships and we need to put this amount
1659 // on the line item rather than the calculated amount.
1660 // This seems to only affect radio link items as that is the use case for the 'quick config'
1661 // set up (which allows a free form field).
1662 // @todo $priceSetID is a pseudoparam for permit override - we should stop passing it where we
1663 // don't specifically need it & find a better way where we do.
1664 $amount_override = NULL;
1666 if ($priceSetID && count(self
::filterPriceFieldsFromParams($priceSetID, $params)) === 1) {
1667 $amount_override = CRM_Utils_Array
::value('total_amount', $params);
1669 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, $amount_override);
1670 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
1671 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
1672 if ($amount_override) {
1673 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule
::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
1679 $params["price_{$id}"] = [$params["price_{$id}"] => 1];
1680 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
1682 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
1683 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
1684 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
1690 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
1691 foreach ($params["price_{$id}"] as $optionId => $option) {
1692 if (!empty($field['options'][$optionId]['tax_rate'])) {
1693 $lineItem = self
::setLineItem($field, $lineItem, $optionId, $totalTax);
1698 return [$params, $lineItem];
1702 * Add the relevant price fields to the form.
1704 * @param \CRM_Core_Form $form
1705 * @param array $feeBlock
1706 * @param bool $validFieldsOnly
1707 * @param string $className
1708 * @param array $validPriceFieldIds
1710 protected static function addPriceFieldsToForm(CRM_Core_Form
$form, $feeBlock, bool $validFieldsOnly, string $className, array $validPriceFieldIds) {
1711 $hideAdminValues = !CRM_Core_Permission
::check('edit contributions');
1712 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
1713 $adminFieldVisible = CRM_Core_Permission
::check('administer CiviCRM');
1714 foreach ($feeBlock as $id => $field) {
1715 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
1716 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
1719 $options = $field['options'] ??
NULL;
1720 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
1721 $userid = $form->getVar('_membershipContactID');
1722 $checklifetime = self
::checkCurrentMembership($options, $userid);
1723 if ($checklifetime) {
1724 $form->assign('ispricelifetime', TRUE);
1728 $formClasses = ['CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'];
1730 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
1733 elseif ($hideAdminValues && !in_array($className, $formClasses)) {
1734 foreach ($options as $key => $currentOption) {
1735 if ($currentOption['visibility_id'] == CRM_Price_BAO_PriceField
::getVisibilityOptionID('admin')) {
1736 unset($options[$key]);
1740 if (!empty($options)) {
1741 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
1742 'price_' . $field['id'],
1745 CRM_Utils_Array
::value('is_required', $field, FALSE),