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;
34 public function __construct() {
35 parent
::__construct();
39 * Takes an associative array and creates a price set object.
41 * @param array $params
42 * (reference) an assoc array of name/value pairs.
44 * @return CRM_Price_DAO_PriceSet
46 public static function create(&$params) {
47 $hook = empty($params['id']) ?
'create' : 'edit';
48 CRM_Utils_Hook
::pre($hook, 'PriceSet', CRM_Utils_Array
::value('id', $params), $params);
50 if (empty($params['id']) && empty($params['name'])) {
51 $params['name'] = CRM_Utils_String
::munge($params['title'], '_', 242);
54 $validatePriceSet = TRUE;
55 if (!empty($params['extends']) && is_array($params['extends'])) {
56 if (!array_key_exists(CRM_Core_Component
::getComponentID('CiviEvent'), $params['extends'])
57 ||
!array_key_exists(CRM_Core_Component
::getComponentID('CiviMember'), $params['extends'])
59 $validatePriceSet = FALSE;
61 $params['extends'] = CRM_Utils_Array
::implodePadded($params['extends']);
64 $priceSetID = $params['id'] ??
NULL;
66 $priceSetBAO = new CRM_Price_BAO_PriceSet();
67 $priceSetBAO->copyValues($params);
68 if (self
::eventPriceSetDomainID()) {
69 $priceSetBAO->domain_id
= CRM_Core_Config
::domainID();
73 CRM_Utils_Hook
::post($hook, 'PriceSet', $priceSetBAO->id
, $priceSetBAO);
74 unset(\Civi
::$statics['CRM_Core_PseudoConstant']);
79 * Fetch object based on array of properties.
81 * @param array $params
82 * (reference ) an assoc array of name/value pairs.
83 * @param array $defaults
84 * (reference ) an assoc array to hold the flattened values.
86 * @return CRM_Price_DAO_PriceSet
88 public static function retrieve(&$params, &$defaults) {
89 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
93 * Update the is_active flag in the db.
96 * Id of the database record.
100 * true if we found and updated the object, else false
102 public static function setIsActive($id, $isActive) {
103 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
107 * Calculate the default price set id
108 * assigned to the contribution/membership etc
110 * @param string $entity
116 public static function getDefaultPriceSet($entity = 'contribution') {
117 if (isset(\Civi
::$statics[__CLASS__
][$entity])) {
118 return \Civi
::$statics[__CLASS__
][$entity];
120 $priceSetName = ($entity === 'membership') ?
'default_membership_type_amount' : 'default_contribution_amount';
123 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
124 FROM civicrm_price_set ps
125 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
126 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
127 WHERE ps.name = '{$priceSetName}'
130 $dao = CRM_Core_DAO
::executeQuery($sql);
131 while ($dao->fetch()) {
132 \Civi
::$statics[__CLASS__
][$entity][$dao->priceFieldValueID
] = [
133 'setID' => $dao->setID
,
134 'priceFieldID' => $dao->priceFieldID
,
135 'name' => $dao->name
,
136 'label' => $dao->label
,
137 'priceFieldValueID' => $dao->priceFieldValueID
,
138 'membership_type_id' => $dao->membership_type_id
,
139 'amount' => $dao->amount
,
140 'financial_type_id' => $dao->financial_type_id
,
144 return \Civi
::$statics[__CLASS__
][$entity];
148 * Get the price set title.
157 public static function getTitle($id) {
158 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
162 * Return a list of all forms which use this price set.
166 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
170 public static function getUsedBy($id, $simpleReturn = FALSE) {
172 $forms = self
::getFormsUsingPriceSet($id);
173 $tables = array_keys($forms);
174 // @todo - this is really clumsy overloading the signature like this. Instead
175 // move towards having a function that does not call reformatUsedByFormsWithEntityData
176 // and call that when that data is not used.
177 if ($simpleReturn == 'table') {
180 // @todo - this is painfully slow in some cases.
183 SELECT cli.entity_table, cli.entity_id
184 FROM civicrm_line_item cli
185 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
186 WHERE cpf.price_set_id = %1";
187 $params = [1 => [$id, 'Integer']];
188 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
189 while ($crmFormDAO->fetch()) {
190 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
191 $tables[] = $crmFormDAO->entity_table
;
197 // @todo - this is really clumsy overloading the signature like this. See above.
198 if ($simpleReturn == 'entity') {
201 $usedBy = self
::reformatUsedByFormsWithEntityData($forms, $usedBy);
207 * Delete the price set, including the fields.
213 * false if fields exist for this set, true if the
214 * set could be deleted
217 public static function deleteSet($id) {
218 // delete price fields
219 $priceField = new CRM_Price_DAO_PriceField();
220 $priceField->price_set_id
= $id;
222 while ($priceField->fetch()) {
223 // delete options first
224 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
227 $set = new CRM_Price_DAO_PriceSet();
229 return $set->delete();
233 * Link the price set with the specified table and id.
235 * @param string $entityTable
236 * @param int $entityId
237 * @param int $priceSetId
241 public static function addTo($entityTable, $entityId, $priceSetId) {
242 // verify that the price set exists
243 $dao = new CRM_Price_DAO_PriceSet();
244 $dao->id
= $priceSetId;
250 $dao = new CRM_Price_DAO_PriceSetEntity();
251 // find if this already exists
252 $dao->entity_id
= $entityId;
253 $dao->entity_table
= $entityTable;
256 // add or update price_set_id
257 $dao->price_set_id
= $priceSetId;
262 * Delete price set for the given entity and id.
264 * @param string $entityTable
265 * @param int $entityId
269 public static function removeFrom($entityTable, $entityId) {
270 $dao = new CRM_Price_DAO_PriceSetEntity();
271 $dao->entity_table
= $entityTable;
272 $dao->entity_id
= $entityId;
273 return $dao->delete();
277 * Find a price_set_id associated with the given table, id and usedFor
278 * Used For value for events:1, contribution:2, membership:3
280 * @param string $entityTable
281 * @param int $entityId
282 * @param int $usedFor
283 * ( price set that extends/used for particular component ).
285 * @param null $isQuickConfig
286 * @param null $setName
289 * price_set_id, or false if none found
291 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
292 if (!$entityTable ||
!$entityId) {
296 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
297 FROM civicrm_price_set ps
298 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
299 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
300 if ($isQuickConfig) {
301 $sql .= ' AND ps.is_quick_config = 0 ';
304 1 => [$entityTable, 'String'],
305 2 => [$entityId, 'Integer'],
308 $sql .= " AND ps.extends LIKE '%%3%' ";
309 $params[3] = [$usedFor, 'Integer'];
312 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
314 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
315 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
319 * Find a price_set_id associated with the given option value or field ID.
321 * @param array $params
322 * (reference) an assoc array of name/value pairs.
323 * array may contain either option id or
327 * price set id on success, null otherwise
329 public static function getSetId(&$params) {
332 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
333 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
334 $fieldValue->id
= $oid;
335 if ($fieldValue->find(TRUE)) {
336 $fid = $fieldValue->price_field_id
;
340 $fid = $params['fid'] ??
NULL;
344 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
351 * Return an associative array of all price sets.
353 * @param bool $withInactive
354 * Whether or not to include inactive entries.
355 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
356 * @param string $column name of the column.
359 * associative array of id => name
361 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE, $column = 'title') {
364 DISTINCT ( price_set_id ) as id, s.{$column}
367 INNER JOIN civicrm_price_field f ON f.price_set_id = s.id
368 INNER JOIN civicrm_price_field_value v ON v.price_field_id = f.id
370 is_quick_config = 0 ";
372 if (!$withInactive) {
373 $query .= ' AND s.is_active = 1 ';
376 if (self
::eventPriceSetDomainID()) {
377 $query .= ' AND s.domain_id = ' . CRM_Core_Config
::domainID();
382 if ($extendComponentName) {
383 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
387 $query .= " AND s.extends LIKE '%$componentId%' ";
389 // Check permissioned financial types
390 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialType, CRM_Core_Action
::ADD
);
391 if ($financialType) {
392 $types = implode(',', array_keys($financialType));
393 $query .= ' AND s.financial_type_id IN (' . $types . ') AND v.financial_type_id IN (' . $types . ') ';
396 // Do not display any price sets
399 $query .= " GROUP BY s.id";
400 $dao = CRM_Core_DAO
::executeQuery($query);
401 while ($dao->fetch()) {
402 $priceSets[$dao->id
] = $dao->$column;
408 * Get price set details.
410 * An array containing price set details (including price fields) is returned
414 * @param bool $required
415 * Appears to have no effect based on reading the code.
416 * @param bool $validOnly
417 * Should only fields where today's date falls within the valid range be returned?
420 * Array consisting of field details
422 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
435 'is_display_amounts',
444 if ($required == TRUE) {
445 $priceFields[] = 'is_required';
449 $select = 'SELECT ' . implode(',', $priceFields);
450 $from = ' FROM civicrm_price_field';
453 1 => [$setID, 'Integer'],
455 $currentTime = date('YmdHis');
457 WHERE price_set_id = %1
459 AND ( active_on IS NULL OR active_on <= {$currentTime} )
464 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
468 $orderBy = ' ORDER BY weight';
470 $sql = $select . $from . $where . $dateSelect . $orderBy;
472 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
474 $isDefaultContributionPriceSet = FALSE;
475 if ('default_contribution_amount' == CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $setID)) {
476 $isDefaultContributionPriceSet = TRUE;
479 $visibility = CRM_Core_PseudoConstant
::visibility('name');
480 while ($dao->fetch()) {
483 $setTree[$setID]['fields'][$fieldID] = [];
484 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
486 foreach ($priceFields as $field) {
487 if ($field == 'id' ||
is_null($dao->$field)) {
491 if ($field == 'visibility_id') {
492 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
494 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
496 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE, FALSE, $isDefaultContributionPriceSet);
499 // also get the pre and post help from this price set
501 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config, min_amount
502 FROM civicrm_price_set
504 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
506 $setTree[$setID]['extends'] = $dao->extends;
507 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
508 $setTree[$setID]['help_pre'] = $dao->help_pre
;
509 $setTree[$setID]['help_post'] = $dao->help_post
;
510 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
511 $setTree[$setID]['min_amount'] = $dao->min_amount
;
517 * Get the Price Field ID.
519 * We call this function when more than one being present would represent an error
520 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
521 * @param array $priceSet
523 * @throws CRM_Core_Exception
526 public static function getOnlyPriceFieldID(array $priceSet) {
527 if (count($priceSet['fields']) > 1) {
528 throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
530 return (int) implode('_', array_keys($priceSet['fields']));
534 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
535 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
536 * @param array $priceSet
538 * @throws CRM_Core_Exception
541 public static function getOnlyPriceFieldValueID(array $priceSet) {
542 $priceFieldID = self
::getOnlyPriceFieldID($priceSet);
543 if (count($priceSet['fields'][$priceFieldID]['options']) > 1) {
544 throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
546 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
550 * Initiate price set such that various non-BAO things are set on the form.
552 * This function is not really a BAO function so the location is misleading.
554 * @param CRM_Core_Form $form
556 * @param string $entityTable
557 * @param bool $validOnly
558 * @param int $priceSetId
561 public static function initSet(&$form, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
563 //check if price set is is_config
564 if (is_numeric($priceSetId)) {
565 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
566 $form->assign('quickConfig', 1);
571 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
572 $entityId = $entity = NULL;
574 switch ($entityTable) {
575 case 'civicrm_event':
576 $entity = 'participant';
577 if (CRM_Utils_System
::getClassName($form) == 'CRM_Event_Form_Participant') {
578 $entityId = $form->_id
;
581 $entityId = $form->_participantId
;
585 case 'civicrm_contribution_page':
586 case 'civicrm_contribution':
587 $entity = 'contribution';
588 $entityId = $form->_id
;
592 if ($entityId && $entity) {
593 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
601 $form->_priceSetId
= $priceSetId;
602 $priceSet = self
::getSetDetail($priceSetId, $required, $validOnly);
603 $form->_priceSet
= $priceSet[$priceSetId] ??
NULL;
604 $form->_values
['fee'] = $form->_priceSet
['fields'] ??
NULL;
606 //get the price set fields participant count.
607 if ($entityTable == 'civicrm_event') {
608 //get option count info.
609 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
610 if ($form->_priceSet
['optionsCountTotal']) {
611 $optionsCountDetails = [];
612 if (!empty($form->_priceSet
['fields'])) {
613 foreach ($form->_priceSet
['fields'] as $field) {
614 foreach ($field['options'] as $option) {
615 $count = CRM_Utils_Array
::value('count', $option, 0);
616 $optionsCountDetails['fields'][$field['id']]['options'][$option['id']] = $count;
620 $form->_priceSet
['optionsCountDetails'] = $optionsCountDetails;
623 //get option max value info.
624 $optionsMaxValueTotal = 0;
625 $optionsMaxValueDetails = [];
627 if (!empty($form->_priceSet
['fields'])) {
628 foreach ($form->_priceSet
['fields'] as $field) {
629 foreach ($field['options'] as $option) {
630 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
631 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
632 $optionsMaxValueTotal +
= $maxVal;
637 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
638 if ($optionsMaxValueTotal) {
639 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
642 $form->set('priceSetId', $form->_priceSetId
);
643 $form->set('priceSet', $form->_priceSet
);
648 * Get line item purchase information.
650 * This function takes the input parameters and interprets out of it what has been purchased.
653 * This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
654 * And, it would make sense to introduce caching into that function and call it from here rather than
655 * require the $fields array which is passed from pillar to post around the form in order to pass it in here.
656 * @param array $params
657 * Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
659 * Line item array to be altered.
660 * @param int $priceSetID
662 * @todo $priceSetID is a pseudoparam for permit override - we should stop passing it where we
663 * don't specifically need it & find a better way where we do.
665 public static function processAmount($fields, &$params, &$lineItem, $priceSetID = NULL) {
667 $totalPrice = $totalTax = 0;
668 foreach ($fields as $id => $field) {
669 if (empty($params["price_{$id}"]) ||
670 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
672 // skip if nothing was submitted for this field
676 list($params, $lineItem, $totalTax, $totalPrice) = self
::getLine($params, $lineItem, $priceSetID, $field, $id, $totalPrice);
680 $totalParticipant = 0;
681 if (is_array($lineItem)) {
682 foreach ($lineItem as $values) {
683 $totalParticipant +
= $values['participant_count'];
684 // This is a bit nasty. The logic of 'quick config' was because price set configuration was
685 // (and still is) too difficult to replace the 'quick config' price set configuration on the contribution
688 // However, because the quick config concept existed all sorts of logic was hung off it
689 // and function behaviour sometimes depends on whether 'price set' is set - although actually it
690 // is always set at the functional level. In this case we are dealing with the default 'quick config'
691 // price set having a label of 'Contribution Amount' which could wind up creating a 'funny looking' label.
692 // The correct answer is probably for it to have an empty label in the DB - the label is never shown so it is a
695 // But, in the interests of being careful when capacity is low - avoiding the known default value
697 // Crucially a test has been added so a better solution can be implemented later with some comfort.
698 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
699 if ($values['label'] !== ts('Contribution Amount')) {
700 $amount_level[] = $values['label'] . ' - ' . (float) $values['qty'];
705 $displayParticipantCount = '';
706 if ($totalParticipant > 0) {
707 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
709 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
710 if (!empty($amount_level)) {
711 $params['amount_level'] = CRM_Utils_Array
::implodePadded($amount_level);
712 if (!empty($displayParticipantCount)) {
713 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
717 $params['amount'] = $totalPrice;
718 $params['tax_amount'] = $totalTax;
722 * Get the text to record for amount level.
724 * @param array $params
725 * Submitted parameters
726 * - priceSetId is required to be set in the calling function
727 * (we don't e-notice check it to enforce that - all payments DO have a price set - even if it is the
728 * default one & this function asks that be set if it is the case).
731 * Text for civicrm_contribution.amount_level field.
733 public static function getAmountLevelText($params) {
734 $priceSetID = $params['priceSetId'];
735 $priceFieldSelection = self
::filterPriceFieldsFromParams($priceSetID, $params);
736 $priceFieldMetadata = self
::getCachedPriceSetDetail($priceSetID);
737 $displayParticipantCount = NULL;
740 foreach ($priceFieldMetadata['fields'] as $field) {
741 if (!empty($priceFieldSelection[$field['id']])) {
743 if ($field['is_enter_qty']) {
744 $qtyString = ' - ' . (float) $params['price_' . $field['id']];
746 // We deliberately & specifically exclude contribution amount as it has a specific meaning.
747 // ie. it represents the default price field for a contribution. Another approach would be not
748 // to give it a label if we don't want it to show.
749 if ($field['label'] !== ts('Contribution Amount')) {
750 $amount_level[] = $field['label'] . $qtyString;
754 return CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
758 * Get the fields relevant to the price field from the parameters.
760 * E.g we are looking for price_5 => 7 out of a big array of input parameters.
762 * @param int $priceSetID
763 * @param array $params
766 * Price fields found in the params array
768 public static function filterPriceFieldsFromParams($priceSetID, $params) {
769 $priceSet = self
::getCachedPriceSetDetail($priceSetID);
771 foreach ($priceSet['fields'] as $field) {
772 if (!empty($params['price_' . $field['id']])) {
773 $return[$field['id']] = $params['price_' . $field['id']];
780 * Wrapper for getSetDetail with caching.
782 * We seem to be passing this array around in a painful way - presumably to avoid the hit
783 * of loading it - so lets make it callable with caching.
785 * Why not just add caching to the other function? We could do - it just seemed a bit unclear the best caching pattern
786 * & the function was already pretty fugly. Also, I feel like we need to migrate the interaction with price-sets into
787 * a more granular interaction - ie. retrieve specific data using specific functions on this class & have the form
788 * think less about the price sets.
790 * @param int $priceSetID
794 public static function getCachedPriceSetDetail($priceSetID) {
795 $cacheKey = __CLASS__
. __FUNCTION__
. '_' . $priceSetID;
796 $cache = CRM_Utils_Cache
::singleton();
797 $values = $cache->get($cacheKey);
798 if (empty($values)) {
799 $data = self
::getSetDetail($priceSetID);
800 $values = $data[$priceSetID];
801 $cache->set($cacheKey, $values);
807 * Build the price set form.
809 * @param CRM_Core_Form $form
813 public static function buildPriceSet(&$form) {
814 $priceSetId = $form->get('priceSetId');
819 $validFieldsOnly = TRUE;
820 $className = CRM_Utils_System
::getClassName($form);
821 if (in_array($className, [
822 'CRM_Contribute_Form_Contribution',
823 'CRM_Member_Form_Membership',
825 $validFieldsOnly = FALSE;
828 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
829 $form->_priceSet
= $priceSet[$priceSetId] ??
NULL;
830 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
831 $form->_quickConfig
= $quickConfig = 0;
832 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
836 $form->assign('quickConfig', $quickConfig);
837 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
838 $form->_quickConfig
= $quickConfig;
841 // Mark which field should have the auto-renew checkbox, if any. CRM-18305
842 if (!empty($form->_membershipTypeValues
) && is_array($form->_membershipTypeValues
)) {
843 $autoRenewMembershipTypes = [];
844 foreach ($form->_membershipTypeValues
as $membershiptTypeValue) {
845 if ($membershiptTypeValue['auto_renew']) {
846 $autoRenewMembershipTypes[] = $membershiptTypeValue['id'];
849 foreach ($form->_priceSet
['fields'] as $field) {
850 if (array_key_exists('options', $field) && is_array($field['options'])) {
851 foreach ($field['options'] as $option) {
852 if (!empty($option['membership_type_id'])) {
853 if (in_array($option['membership_type_id'], $autoRenewMembershipTypes)) {
854 $form->_priceSet
['auto_renew_membership_field'] = $field['id'];
855 // Only one field can offer auto_renew memberships, so break here.
863 $form->assign('priceSet', $form->_priceSet
);
865 $component = 'contribution';
866 if ($className == 'CRM_Member_Form_Membership') {
867 $component = 'membership';
870 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
871 $feeBlock = &$form->_values
['fee'];
872 if (!empty($form->_useForMember
)) {
873 $component = 'membership';
877 $feeBlock = &$form->_priceSet
['fields'];
880 self
::applyACLFinancialTypeStatusToFeeBlock($feeBlock);
881 // Call the buildAmount hook.
882 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
884 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
885 $adminFieldVisible = FALSE;
886 if (CRM_Core_Permission
::check('administer CiviCRM')) {
887 $adminFieldVisible = TRUE;
890 $hideAdminValues = TRUE;
891 if (CRM_Core_Permission
::check('edit contributions')) {
892 $hideAdminValues = FALSE;
895 foreach ($feeBlock as $id => $field) {
896 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
897 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
900 $options = $field['options'] ??
NULL;
901 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
902 $userid = $form->getVar('_membershipContactID');
903 $checklifetime = self
::checkCurrentMembership($options, $userid);
904 if ($checklifetime) {
905 $form->assign('ispricelifetime', TRUE);
909 $formClasses = ['CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'];
911 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
914 elseif ($hideAdminValues && !in_array($className, $formClasses)) {
915 foreach ($options as $key => $currentOption) {
916 if ($currentOption['visibility_id'] == CRM_Price_BAO_PriceField
::getVisibilityOptionID('admin')) {
917 unset($options[$key]);
921 if (!empty($options)) {
922 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
923 'price_' . $field['id'],
926 CRM_Utils_Array
::value('is_required', $field, FALSE),
936 * Apply ACLs on Financial Type to the price options in a fee block.
938 * @param array $feeBlock
939 * Fee block: array of price fields.
943 public static function applyACLFinancialTypeStatusToFeeBlock(&$feeBlock) {
944 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
945 foreach ($feeBlock as $key => $value) {
946 foreach ($value['options'] as $k => $options) {
947 if (!CRM_Core_Permission
::check('add contributions of type ' . CRM_Contribute_PseudoConstant
::financialType($options['financial_type_id']))) {
948 unset($feeBlock[$key]['options'][$k]);
951 if (empty($feeBlock[$key]['options'])) {
952 unset($feeBlock[$key]);
959 * Check the current Membership having end date null.
961 * @param array $options
963 * Probably actually contact ID.
967 public static function checkCurrentMembership(&$options, $userid) {
968 if (!$userid ||
empty($options)) {
971 static $_contact_memberships = [];
972 $checkLifetime = FALSE;
973 foreach ($options as $key => $value) {
974 if (!empty($value['membership_type_id'])) {
975 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
976 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
978 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
979 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
980 unset($options[$key]);
981 $checkLifetime = TRUE;
985 if ($checkLifetime) {
994 * Set daefult the price set fields.
996 * @param CRM_Core_Form $form
1001 public static function setDefaultPriceSet(&$form, &$defaults) {
1002 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
1006 foreach ($form->_priceSet
['fields'] as $val) {
1007 foreach ($val['options'] as $keys => $values) {
1008 // build price field index which is passed via URL
1009 // url format will be appended by "&price_5=11"
1010 $priceFieldName = 'price_' . $values['price_field_id'];
1011 $priceFieldValue = self
::getPriceFieldValueFromURL($form, $priceFieldName);
1012 if (!empty($priceFieldValue)) {
1013 self
::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $defaults);
1014 // break here to prevent overwriting of default due to 'is_default'
1015 // option configuration. The value sent via URL get's higher priority.
1018 elseif ($values['is_default']) {
1019 self
::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $defaults);
1027 * Get the value of price field if passed via url
1029 * @param string $priceFieldName
1030 * @param string $priceFieldValue
1031 * @param string $priceFieldType
1032 * @param array $defaults
1036 public static function setDefaultPriceSetField($priceFieldName, $priceFieldValue, $priceFieldType, &$defaults) {
1037 if ($priceFieldType == 'CheckBox') {
1038 $defaults[$priceFieldName][$priceFieldValue] = 1;
1041 $defaults[$priceFieldName] = $priceFieldValue;
1046 * Get the value of price field if passed via url
1048 * @param CRM_Core_Form $form
1049 * @param string $priceFieldName
1051 * @return mixed $priceFieldValue
1053 public static function getPriceFieldValueFromURL(&$form, $priceFieldName) {
1054 $priceFieldValue = CRM_Utils_Request
::retrieve($priceFieldName, 'String', $form, FALSE, NULL, 'GET');
1055 if (!empty($priceFieldValue)) {
1056 return $priceFieldValue;
1061 * Supports event create function by setting up required price sets, not tested but expect
1062 * it will work for contribution page
1063 * @param array $params
1064 * As passed to api/bao create fn.
1065 * @param CRM_Core_DAO $entity
1066 * Object for given entity.
1067 * @param string $entityName
1068 * Name of entity - e.g event.
1070 public static function setPriceSets(&$params, $entity, $entityName) {
1071 if (empty($params['price_set_id']) ||
!is_array($params['price_set_id'])) {
1074 // CRM-14069 note that we may as well start by assuming more than one.
1075 // currently the form does not pass in as an array & will be skipped
1076 // test is passing in as an array but I feel the api should have a metadata that allows
1077 // transform of single to array - seems good for managing transitions - in which case all api
1078 // calls that set price_set_id will hit this
1079 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1080 // all separated values, strings, json half-separated values (in participant we hit this)
1081 // to be converted to json @ api layer
1082 $pse = new CRM_Price_DAO_PriceSetEntity();
1083 $pse->entity_table
= 'civicrm_' . $entityName;
1084 $pse->entity_id
= $entity->id
;
1085 while ($pse->fetch()) {
1086 if (!in_array($pse->price_set_id
, $params['price_set_id'])) {
1087 // note an even more aggressive form of this deletion currently happens in event form
1088 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1089 // on the participant record
1090 if (CRM_Price_BAO_PriceSet
::removeFrom('civicrm_' . $entityName, $entity->id
)) {
1091 CRM_Core_BAO_Discount
::del($entity->id
, 'civicrm_' . $entityName);
1095 foreach ($params['price_set_id'] as $priceSetID) {
1096 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $entityName, $entity->id
, $priceSetID);
1097 //@todo - how should we do this - copied from form
1098 //if (!empty($params['price_field_id'])) {
1099 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1100 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1106 * Get field ids of a price set.
1112 * Array of the field ids
1115 public static function getFieldIds($id) {
1116 $priceField = new CRM_Price_DAO_PriceField();
1117 $priceField->price_set_id
= $id;
1118 $priceField->find();
1119 while ($priceField->fetch()) {
1120 $var[] = $priceField->id
;
1126 * Copy a price set, including all the fields
1129 * The price set id to copy.
1131 * @return CRM_Price_DAO_PriceSet
1133 public static function copy($id) {
1134 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1135 $priceSet = civicrm_api3('PriceSet', 'getsingle', ['id' => $id]);
1137 $newTitle = preg_replace('/\[Copy id \d+\]$/', "", $priceSet['title']);
1138 $title = ts('[Copy id %1]', [1 => $maxId +
1]);
1141 'title' => trim($newTitle) . ' ' . $title,
1142 'name' => substr($priceSet['name'], 0, 20) . 'price_set_' . ($maxId +
1),
1146 $copy = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1152 //copying all the blocks pertaining to the price set
1153 $copyPriceField = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1154 ['price_set_id' => $id],
1155 ['price_set_id' => $copy->id
]
1157 if (!empty($copyPriceField)) {
1158 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1160 //copy option group and values
1161 foreach ($price as $originalId => $copyId) {
1162 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1163 ['price_field_id' => $originalId],
1164 ['price_field_id' => $copyId]
1170 CRM_Utils_Hook
::copy('Set', $copy);
1171 unset(\Civi
::$statics['CRM_Core_PseudoConstant']);
1176 * check price set permission.
1182 * @throws \CRM_Core_Exception
1184 public static function checkPermission($sid) {
1185 if ($sid && self
::eventPriceSetDomainID()) {
1186 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1187 if (CRM_Core_Config
::domainID() != $domain_id) {
1188 CRM_Core_Error
::statusBounce(ts('You do not have permission to access this page.'));
1195 * Get the sum of participant count
1196 * for all fields of given price set.
1201 * @param bool $onlyActive
1203 * @return int|null|string
1205 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1213 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1216 static $pricesetFieldCount = [];
1217 if (!isset($pricesetFieldCount[$sid])) {
1219 SELECT sum(value.count) as totalCount
1220 FROM civicrm_price_field_value value
1221 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1222 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1226 $count = CRM_Core_DAO
::singleValueQuery($sql, [1 => [$sid, 'Positive']]);
1227 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1230 return $pricesetFieldCount[$sid];
1238 public static function getMembershipCount($ids) {
1240 SELECT count( pfv.id ) AS count, mt.member_of_contact_id AS id
1241 FROM civicrm_price_field_value pfv
1242 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1243 WHERE pfv.id IN ( $ids )
1244 GROUP BY mt.member_of_contact_id ";
1246 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1249 while ($crmDAO->fetch()) {
1250 $count[$crmDAO->id
] = $crmDAO->count
;
1257 * Check if auto renew option should be shown.
1259 * The auto-renew option should be visible if membership types associated with all the fields has
1260 * been set for auto-renew option.
1262 * Auto renew checkbox should be frozen if for all the membership type auto renew is required
1264 * @param int $priceSetId
1268 * $autoRenewOption ( 0:hide, 1:optional 2:required )
1270 public static function checkAutoRenewForPriceSet($priceSetId) {
1271 $query = 'SELECT DISTINCT mt.auto_renew, mt.duration_interval, mt.duration_unit,
1272 pf.html_type, pf.id as price_field_id
1273 FROM civicrm_price_field_value pfv
1274 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1275 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1276 WHERE pf.price_set_id = %1
1277 AND pf.is_active = 1
1278 AND pfv.is_active = 1
1279 ORDER BY price_field_id';
1281 $params = [1 => [$priceSetId, 'Integer']];
1283 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1285 //CRM-18050: Check count of price set fields which has been set with auto-renew option.
1286 //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.
1291 $autoRenewOption = 2;
1293 while ($dao->fetch()) {
1294 if (!$dao->auto_renew
) {
1295 // If any one can't be renewed none can.
1298 if ($dao->auto_renew
== 1) {
1299 $autoRenewOption = 1;
1302 if ($dao->html_type
== 'Checkbox' && !in_array($dao->duration_interval
. $dao->duration_unit
, $priceFields[$dao->price_field_id
])) {
1303 // Checkbox fields cannot support auto-renew if they have more than one duration configuration
1304 // as more than one can be selected. Radio and select are either-or so they can have more than one duration.
1307 $priceFields[$dao->price_field_id
][] = $dao->duration_interval
. $dao->duration_unit
;
1308 foreach ($priceFields as $priceFieldID => $durations) {
1309 if ($priceFieldID != $dao->price_field_id
&& !in_array($dao->duration_interval
. $dao->duration_unit
, $durations)) {
1310 // Another price field has a duration configuration that differs so we can't offer auto-renew.
1316 return $autoRenewOption;
1320 * Retrieve auto renew frequency and interval.
1322 * @param int $priceSetId
1326 * associate array of frequency interval and unit
1328 public static function getRecurDetails($priceSetId) {
1329 $query = 'SELECT mt.duration_interval, mt.duration_unit
1330 FROM civicrm_price_field_value pfv
1331 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1332 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1333 WHERE pf.price_set_id = %1 LIMIT 1';
1335 $params = [1 => [$priceSetId, 'Integer']];
1336 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1338 return [$dao->duration_interval
, $dao->duration_unit
];
1344 public static function eventPriceSetDomainID() {
1345 return Civi
::settings()->get('event_price_set_domain_id');
1349 * Update the is_quick_config flag in the db.
1352 * Id of the database record.
1353 * @param bool $isQuickConfig we want to set the is_quick_config field.
1354 * Value we want to set the is_quick_config field.
1357 * true if we found and updated the object, else false
1359 public static function setIsQuickConfig($id, $isQuickConfig) {
1360 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1364 * Check if price set id provides option for user to select both auto-renew and non-auto-renew memberships
1370 public static function isMembershipPriceSetContainsMixOfRenewNonRenew($id) {
1371 $membershipTypes = self
::getMembershipTypesFromPriceSet($id);
1372 if (!empty($membershipTypes['autorenew']) && !empty($membershipTypes['non_renew'])) {
1379 * Get an array of the membership types in a price set.
1384 * Membership types in the price set
1386 public static function getMembershipTypesFromPriceSet($id) {
1388 = "SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1389 FROM civicrm_price_field_value pfv
1390 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1391 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1392 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1396 $params = [1 => [$id, 'Integer']];
1397 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1399 $membershipTypes = [
1402 'autorenew_required' => [],
1403 'autorenew_optional' => [],
1405 while ($dao->fetch()) {
1406 if (empty($dao->membership_type_id
)) {
1409 $membershipTypes['all'][] = $dao->membership_type_id
;
1410 if (!empty($dao->auto_renew
)) {
1411 $membershipTypes['autorenew'][] = $dao->membership_type_id
;
1412 if ($dao->auto_renew
== 2) {
1413 $membershipTypes['autorenew_required'][] = $dao->membership_type_id
;
1416 $membershipTypes['autorenew_optional'][] = $dao->membership_type_id
;
1420 $membershipTypes['non_renew'][] = $dao->membership_type_id
;
1423 return $membershipTypes;
1427 * Copy priceSet when event/contibution page is copied
1429 * @param string $baoName
1432 * Old event/contribution page id.
1434 * Newly created event/contribution page id.
1436 public static function copyPriceSet($baoName, $id, $newId) {
1437 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1439 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1440 if ($isQuickConfig) {
1441 $copyPriceSet = CRM_Price_BAO_PriceSet
::copy($priceSetId);
1442 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1445 $copyPriceSet = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1448 'entity_table' => $baoName,
1450 ['entity_id' => $newId]
1453 // copy event discount
1454 if ($baoName == 'civicrm_event') {
1455 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1456 foreach ($discount as $discountId => $setId) {
1458 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1460 CRM_Core_DAO
::copyGeneric(
1461 'CRM_Core_DAO_Discount',
1463 'id' => $discountId,
1466 'entity_id' => $newId,
1467 'price_set_id' => $copyPriceSet->id
,
1476 * Function to set tax_amount and tax_rate in LineItem.
1478 * @param array $field
1479 * @param array $lineItem
1480 * @param int $optionValueId
1481 * @param float $totalTax
1485 public static function setLineItem($field, $lineItem, $optionValueId, &$totalTax) {
1486 // Here we round - i.e. after multiplying by quantity
1487 if ($field['html_type'] == 'Text') {
1488 $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
1491 $taxAmount = $field['options'][$optionValueId]['tax_amount'];
1493 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1494 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1495 $lineItem[$optionValueId]['tax_rate'] = $taxRate;
1496 $totalTax +
= $taxAmount;
1501 * Get the first price set value IDs from a parameters array.
1503 * In practice this is really used when we only expect one to exist.
1505 * @param array $params
1508 * Array of the ids of the price set values.
1510 public static function parseFirstPriceSetValueIDFromParams($params) {
1511 $priceSetValueIDs = self
::parsePriceSetValueIDsFromParams($params);
1512 return reset($priceSetValueIDs);
1516 * Get the price set value IDs from a set of parameters
1518 * @param array $params
1521 * Array of the ids of the price set values.
1523 public static function parsePriceSetValueIDsFromParams($params) {
1524 $priceSetParams = self
::parsePriceSetArrayFromParams($params);
1525 $priceSetValueIDs = [];
1526 foreach ($priceSetParams as $priceSetParam) {
1527 foreach (array_keys($priceSetParam) as $priceValueID) {
1528 $priceSetValueIDs[] = $priceValueID;
1531 return $priceSetValueIDs;
1535 * Get the price set value IDs from a set of parameters
1537 * @param array $params
1540 * Array of price fields filtered from the params.
1542 public static function parsePriceSetArrayFromParams($params) {
1543 $priceSetParams = [];
1544 foreach ($params as $field => $value) {
1545 $parts = explode('_', $field);
1546 if (count($parts) == 2 && $parts[0] == 'price' && is_numeric($parts[1]) && is_array($value)) {
1547 $priceSetParams[$field] = $value;
1550 return $priceSetParams;
1554 * Get non-deductible amount from price options
1556 * @param int $priceSetId
1557 * @param array $lineItem
1560 * calculated non-deductible amount.
1562 public static function getNonDeductibleAmountFromPriceSet($priceSetId, $lineItem) {
1563 $nonDeductibleAmount = 0;
1564 if (!empty($lineItem[$priceSetId])) {
1565 foreach ($lineItem[$priceSetId] as $options) {
1566 $nonDeductibleAmount +
= $options['non_deductible_amount'] * $options['qty'];
1570 return $nonDeductibleAmount;
1574 * Get an array of all forms using a given price set.
1579 * Pages using the price set, keyed by type. e.g
1581 * 'civicrm_contribution_page' => array(2,5,6),
1582 * 'civicrm_event' => array(5,6),
1583 * 'civicrm_event_template' => array(7),
1586 public static function getFormsUsingPriceSet($id) {
1589 SELECT entity_table, entity_id
1590 FROM civicrm_price_set_entity
1591 WHERE price_set_id = %1";
1592 $params = [1 => [$id, 'Integer']];
1593 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1595 while ($crmFormDAO->fetch()) {
1596 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
1602 * @param array $forms
1603 * Array of forms that use a price set keyed by entity. e.g
1605 * 'civicrm_contribution_page' => array(2,5,6),
1606 * 'civicrm_event' => array(5,6),
1607 * 'civicrm_event_template' => array(7),
1611 * Array of entities suppliemented with per entity information.
1613 * array('civicrm_event' => array(7 => array('title' => 'x'...))
1615 * @throws \Exception
1617 protected static function reformatUsedByFormsWithEntityData($forms) {
1619 foreach ($forms as $table => $entities) {
1621 case 'civicrm_event':
1622 $ids = implode(',', $entities);
1623 $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
1624 FROM civicrm_event ce
1625 LEFT JOIN civicrm_option_value ON
1626 ( ce.event_type_id = civicrm_option_value.value )
1627 LEFT JOIN civicrm_option_group ON
1628 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
1630 civicrm_option_group.name = 'event_type' AND
1633 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1634 while ($crmDAO->fetch()) {
1635 if ($crmDAO->isTemplate
) {
1636 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
1637 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
1638 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
1641 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
1642 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
1643 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
1644 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
1645 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
1650 case 'civicrm_contribution_page':
1651 $ids = implode(',', $entities);
1652 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
1653 FROM civicrm_contribution_page cp, civicrm_financial_type ct
1654 WHERE ct.id = cp.financial_type_id AND
1657 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1658 while ($crmDAO->fetch()) {
1659 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
1660 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
1661 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
1662 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
1666 case 'civicrm_contribution':
1667 case 'civicrm_membership':
1668 case 'civicrm_participant':
1669 $usedBy[$table] = 1;
1673 throw new CRM_Core_Exception("$table is not supported in PriceSet::usedBy()");
1681 * Get the relevant line item.
1683 * Note this is part of code being cleaned up / refactored & may change.
1685 * @param array $params
1686 * @param array $lineItem
1687 * @param int $priceSetID
1688 * @param array $field
1690 * @param float $totalPrice
1694 public static function getLine(&$params, &$lineItem, $priceSetID, $field, $id, $totalPrice): array {
1696 switch ($field['html_type']) {
1698 $firstOption = reset($field['options']);
1699 $params["price_{$id}"] = [$firstOption['id'] => $params["price_{$id}"]];
1700 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, CRM_Utils_Array
::value('partial_payment_total', $params));
1701 $optionValueId = key($field['options']);
1703 if (CRM_Utils_Array
::value('name', $field['options'][$optionValueId]) === 'contribution_amount') {
1704 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
1705 if (array_key_exists($params['financial_type_id'], $taxRates)) {
1706 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
1707 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($field['options'][$optionValueId]['amount'], $field['options'][$optionValueId]['tax_rate']);
1708 $field['options'][$optionValueId]['tax_amount'] = $taxAmount['tax_amount'];
1711 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
1712 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
1714 $totalPrice +
= $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[key($field['options'])]);
1718 //special case if user select -none-
1719 if ($params["price_{$id}"] <= 0) {
1722 $params["price_{$id}"] = [$params["price_{$id}"] => 1];
1723 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
1725 // CRM-18701 Sometimes the amount in the price set is overridden by the amount on the form.
1726 // This is notably the case with memberships and we need to put this amount
1727 // on the line item rather than the calculated amount.
1728 // This seems to only affect radio link items as that is the use case for the 'quick config'
1729 // set up (which allows a free form field).
1730 // @todo $priceSetID is a pseudoparam for permit override - we should stop passing it where we
1731 // don't specifically need it & find a better way where we do.
1732 $amount_override = NULL;
1734 if ($priceSetID && count(self
::filterPriceFieldsFromParams($priceSetID, $params)) === 1) {
1735 $amount_override = CRM_Utils_Array
::value('partial_payment_total', $params, CRM_Utils_Array
::value('total_amount', $params));
1737 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, $amount_override);
1738 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
1739 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
1740 if ($amount_override) {
1741 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule
::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
1744 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
1748 $params["price_{$id}"] = [$params["price_{$id}"] => 1];
1749 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
1751 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, CRM_Utils_Array
::value('partial_payment_total', $params));
1752 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
1753 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
1755 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
1760 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, CRM_Utils_Array
::value('partial_payment_total', $params));
1761 foreach ($params["price_{$id}"] as $optionId => $option) {
1762 if (!empty($field['options'][$optionId]['tax_rate'])) {
1763 $lineItem = self
::setLineItem($field, $lineItem, $optionId, $totalTax);
1765 $totalPrice +
= $lineItem[$optionId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionId]);
1769 return [$params, $lineItem, $totalTax, $totalPrice];