Merge pull request #22333 from mlutfy/fixTsRecaptcha
[civicrm-core.git] / CRM / Price / BAO / PriceSet.php
CommitLineData
6a488035
TO
1<?php
2/*
bc77d7c0
TO
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
e70a7fc0 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
18/**
1bde39c7 19 * Business object for managing price sets.
6a488035
TO
20 *
21 */
9da8dc8c 22class CRM_Price_BAO_PriceSet extends CRM_Price_DAO_PriceSet {
6a488035 23
71ba92c4 24 /**
fe482240 25 * Static field for default price set details.
71ba92c4
PN
26 *
27 * @var array
71ba92c4 28 */
971e129b 29 public static $_defaultPriceSet = NULL;
71ba92c4 30
6a488035 31 /**
fe482240 32 * Class constructor.
6a488035 33 */
00be9182 34 public function __construct() {
6a488035
TO
35 parent::__construct();
36 }
37
38 /**
fe482240 39 * Takes an associative array and creates a price set object.
6a488035 40 *
414c1420
TO
41 * @param array $params
42 * (reference) an assoc array of name/value pairs.
6a488035 43 *
16b10e64 44 * @return CRM_Price_DAO_PriceSet
6a488035 45 */
00be9182 46 public static function create(&$params) {
214d5f51 47 $hook = empty($params['id']) ? 'create' : 'edit';
48 CRM_Utils_Hook::pre($hook, 'PriceSet', CRM_Utils_Array::value('id', $params), $params);
49
22e263ad 50 if (empty($params['id']) && empty($params['name'])) {
e0c1764e
EM
51 $params['name'] = CRM_Utils_String::munge($params['title'], '_', 242);
52 }
e68e1c9a
PN
53 $priceSetID = NULL;
54 $validatePriceSet = TRUE;
e10ac060 55 if (!empty($params['extends']) && is_array($params['extends'])) {
e68e1c9a
PN
56 if (!array_key_exists(CRM_Core_Component::getComponentID('CiviEvent'), $params['extends'])
57 || !array_key_exists(CRM_Core_Component::getComponentID('CiviMember'), $params['extends'])
58 ) {
59 $validatePriceSet = FALSE;
60 }
076809e3
JV
61 $params['extends'] = CRM_Utils_Array::implodePadded($params['extends']);
62 }
e68e1c9a 63 else {
9c1bc317 64 $priceSetID = $params['id'] ?? NULL;
e68e1c9a 65 }
9da8dc8c 66 $priceSetBAO = new CRM_Price_BAO_PriceSet();
6a488035
TO
67 $priceSetBAO->copyValues($params);
68 if (self::eventPriceSetDomainID()) {
69 $priceSetBAO->domain_id = CRM_Core_Config::domainID();
70 }
214d5f51 71 $priceSetBAO->save();
72
73 CRM_Utils_Hook::post($hook, 'PriceSet', $priceSetBAO->id, $priceSetBAO);
4f238b49 74 unset(\Civi::$statics['CRM_Core_PseudoConstant']);
214d5f51 75 return $priceSetBAO;
6a488035
TO
76 }
77
78 /**
fe482240 79 * Fetch object based on array of properties.
6a488035 80 *
414c1420
TO
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.
6a488035 85 *
16b10e64 86 * @return CRM_Price_DAO_PriceSet
6a488035 87 */
00be9182 88 public static function retrieve(&$params, &$defaults) {
9da8dc8c 89 return CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
6a488035
TO
90 }
91
92 /**
fe482240 93 * Update the is_active flag in the db.
6a488035 94 *
414c1420
TO
95 * @param int $id
96 * Id of the database record.
6c8f6e67
EM
97 * @param $isActive
98 *
8a4fede3 99 * @return bool
100 * true if we found and updated the object, else false
6a488035 101 */
00be9182 102 public static function setIsActive($id, $isActive) {
9da8dc8c 103 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
6a488035
TO
104 }
105
106 /**
107 * Calculate the default price set id
108 * assigned to the contribution/membership etc
109 *
110 * @param string $entity
111 *
a6c01b45
CW
112 * @return array
113 * default price set
6a488035 114 *
6a488035
TO
115 */
116 public static function getDefaultPriceSet($entity = 'contribution') {
63148832 117 if (isset(\Civi::$statics[__CLASS__][$entity])) {
118 return \Civi::$statics[__CLASS__][$entity];
6a488035 119 }
63148832 120 $priceSetName = ($entity === 'membership') ? 'default_membership_type_amount' : 'default_contribution_amount';
6a488035
TO
121
122 $sql = "
82cc6775 123SELECT 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
6a488035
TO
124FROM civicrm_price_set ps
125LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
126LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
63148832 127WHERE ps.name = '{$priceSetName}'
6a488035
TO
128";
129
130 $dao = CRM_Core_DAO::executeQuery($sql);
6a488035 131 while ($dao->fetch()) {
63148832 132 \Civi::$statics[__CLASS__][$entity][$dao->priceFieldValueID] = [
353ffa53
TO
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,
be2fb01f 141 ];
6a488035
TO
142 }
143
63148832 144 return \Civi::$statics[__CLASS__][$entity];
6a488035
TO
145 }
146
147 /**
148 * Get the price set title.
149 *
414c1420
TO
150 * @param int $id
151 * Id of price set.
6a488035 152 *
a6c01b45
CW
153 * @return string
154 * title
6a488035 155 *
6a488035
TO
156 */
157 public static function getTitle($id) {
9da8dc8c 158 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
6a488035
TO
159 }
160
161 /**
162 * Return a list of all forms which use this price set.
163 *
414c1420
TO
164 * @param int $id
165 * Id of price set.
e0c1764e 166 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
6a488035
TO
167 *
168 * @return array
169 */
1bde39c7 170 public static function getUsedBy($id, $simpleReturn = FALSE) {
be2fb01f 171 $usedBy = [];
f5b8da4b 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.
6a488035
TO
177 if ($simpleReturn == 'table') {
178 return $tables;
179 }
f5b8da4b 180 // @todo - this is painfully slow in some cases.
6a488035
TO
181 if (empty($forms)) {
182 $queryString = "
183SELECT cli.entity_table, cli.entity_id
184FROM civicrm_line_item cli
185LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
186WHERE cpf.price_set_id = %1";
be2fb01f 187 $params = [1 => [$id, 'Integer']];
6a488035
TO
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;
192 }
193 if (empty($forms)) {
194 return $usedBy;
195 }
196 }
f5b8da4b 197 // @todo - this is really clumsy overloading the signature like this. See above.
6a488035
TO
198 if ($simpleReturn == 'entity') {
199 return $forms;
200 }
f5b8da4b 201 $usedBy = self::reformatUsedByFormsWithEntityData($forms, $usedBy);
6a488035
TO
202
203 return $usedBy;
204 }
205
206 /**
9d8f190f 207 * Delete the price set, including the fields.
6a488035 208 *
414c1420
TO
209 * @param int $id
210 * Price Set id.
6a488035 211 *
acb1052e 212 * @return bool
a6c01b45 213 * false if fields exist for this set, true if the
16b10e64 214 * set could be deleted
6a488035 215 *
6a488035
TO
216 */
217 public static function deleteSet($id) {
6a488035 218 // delete price fields
9da8dc8c 219 $priceField = new CRM_Price_DAO_PriceField();
6a488035
TO
220 $priceField->price_set_id = $id;
221 $priceField->find();
222 while ($priceField->fetch()) {
223 // delete options first
9da8dc8c 224 CRM_Price_BAO_PriceField::deleteField($priceField->id);
6a488035
TO
225 }
226
9da8dc8c 227 $set = new CRM_Price_DAO_PriceSet();
6a488035
TO
228 $set->id = $id;
229 return $set->delete();
230 }
231
232 /**
fe482240 233 * Link the price set with the specified table and id.
6a488035
TO
234 *
235 * @param string $entityTable
414c1420
TO
236 * @param int $entityId
237 * @param int $priceSetId
6a488035
TO
238 *
239 * @return bool
240 */
241 public static function addTo($entityTable, $entityId, $priceSetId) {
242 // verify that the price set exists
9da8dc8c 243 $dao = new CRM_Price_DAO_PriceSet();
6a488035
TO
244 $dao->id = $priceSetId;
245 if (!$dao->find()) {
246 return FALSE;
247 }
248 unset($dao);
249
9da8dc8c 250 $dao = new CRM_Price_DAO_PriceSetEntity();
6a488035
TO
251 // find if this already exists
252 $dao->entity_id = $entityId;
253 $dao->entity_table = $entityTable;
254 $dao->find(TRUE);
255
256 // add or update price_set_id
257 $dao->price_set_id = $priceSetId;
258 return $dao->save();
259 }
260
261 /**
fe482240 262 * Delete price set for the given entity and id.
6a488035
TO
263 *
264 * @param string $entityTable
414c1420 265 * @param int $entityId
77b97be7
EM
266 *
267 * @return mixed
6a488035
TO
268 */
269 public static function removeFrom($entityTable, $entityId) {
353ffa53 270 $dao = new CRM_Price_DAO_PriceSetEntity();
6a488035 271 $dao->entity_table = $entityTable;
353ffa53 272 $dao->entity_id = $entityId;
6a488035
TO
273 return $dao->delete();
274 }
275
276 /**
1bde39c7 277 * Find a price_set_id associated with the given table, id and usedFor
6a488035
TO
278 * Used For value for events:1, contribution:2, membership:3
279 *
280 * @param string $entityTable
77b97be7 281 * @param int $entityId
414c1420
TO
282 * @param int $usedFor
283 * ( price set that extends/used for particular component ).
77b97be7
EM
284 *
285 * @param null $isQuickConfig
286 * @param null $setName
6a488035 287 *
df8d3074 288 * @return int|false
72b3a70c 289 * price_set_id, or false if none found
6a488035
TO
290 */
291 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
292 if (!$entityTable || !$entityId) {
293 return FALSE;
294 }
295
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 ';
302 }
be2fb01f
CW
303 $params = [
304 1 => [$entityTable, 'String'],
305 2 => [$entityId, 'Integer'],
306 ];
6a488035
TO
307 if ($usedFor) {
308 $sql .= " AND ps.extends LIKE '%%3%' ";
be2fb01f 309 $params[3] = [$usedFor, 'Integer'];
6a488035
TO
310 }
311
312 $dao = CRM_Core_DAO::executeQuery($sql, $params);
313 $dao->fetch();
314 $setName = (isset($dao->price_set_name)) ? $dao->price_set_name : FALSE;
315 return (isset($dao->price_set_id)) ? $dao->price_set_id : FALSE;
316 }
317
318 /**
fe482240 319 * Find a price_set_id associated with the given option value or field ID.
6a488035 320 *
414c1420
TO
321 * @param array $params
322 * (reference) an assoc array of name/value pairs.
6a488035
TO
323 * array may contain either option id or
324 * price field id
325 *
e97c66ff 326 * @return int|null
72b3a70c 327 * price set id on success, null otherwise
6a488035
TO
328 */
329 public static function getSetId(&$params) {
330 $fid = NULL;
331
332 if ($oid = CRM_Utils_Array::value('oid', $params)) {
9da8dc8c 333 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
6a488035
TO
334 $fieldValue->id = $oid;
335 if ($fieldValue->find(TRUE)) {
336 $fid = $fieldValue->price_field_id;
337 }
338 }
339 else {
9c1bc317 340 $fid = $params['fid'] ?? NULL;
6a488035
TO
341 }
342
343 if (isset($fid)) {
9da8dc8c 344 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
6a488035
TO
345 }
346
347 return NULL;
348 }
349
350 /**
fe482240 351 * Return an associative array of all price sets.
6a488035 352 *
414c1420
TO
353 * @param bool $withInactive
354 * Whether or not to include inactive entries.
77b97be7 355 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
6a3d8d2d 356 * @param string $column name of the column.
6a488035 357 *
a6c01b45
CW
358 * @return array
359 * associative array of id => name
6a488035 360 */
6a3d8d2d
WA
361 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE, $column = 'title') {
362 $query = "
6a488035 363 SELECT
75d6d479 364 DISTINCT ( price_set_id ) as id, s.{$column}
6a488035 365 FROM
53df1142
E
366 civicrm_price_set s
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
6a488035 369 WHERE
75d6d479 370 is_quick_config = 0 ";
6a488035
TO
371
372 if (!$withInactive) {
53df1142 373 $query .= ' AND s.is_active = 1 ';
6a488035
TO
374 }
375
376 if (self::eventPriceSetDomainID()) {
53df1142 377 $query .= ' AND s.domain_id = ' . CRM_Core_Config::domainID();
6a488035
TO
378 }
379
be2fb01f 380 $priceSets = [];
6a488035
TO
381
382 if ($extendComponentName) {
383 $componentId = CRM_Core_Component::getComponentID($extendComponentName);
384 if (!$componentId) {
385 return $priceSets;
386 }
53df1142 387 $query .= " AND s.extends LIKE '%$componentId%' ";
6a488035 388 }
53df1142 389 // Check permissioned financial types
573fd305 390 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialType, CRM_Core_Action::ADD);
53df1142 391 if ($financialType) {
40c655aa 392 $types = implode(',', array_keys($financialType));
53df1142
E
393 $query .= ' AND s.financial_type_id IN (' . $types . ') AND v.financial_type_id IN (' . $types . ') ';
394 }
395 else {
c5c263ca
AH
396 // Do not display any price sets
397 $query .= " AND 0 ";
53df1142
E
398 }
399 $query .= " GROUP BY s.id";
6a488035
TO
400 $dao = CRM_Core_DAO::executeQuery($query);
401 while ($dao->fetch()) {
6a3d8d2d 402 $priceSets[$dao->id] = $dao->$column;
6a488035
TO
403 }
404 return $priceSets;
405 }
406
407 /**
fe482240 408 * Get price set details.
6a488035
TO
409 *
410 * An array containing price set details (including price fields) is returned
411 *
100fef9d 412 * @param int $setID
003ca729 413 * Price Set ID.
2a6da8d7 414 * @param bool $required
003ca729 415 * Appears to have no effect based on reading the code.
e5467560 416 * @param bool $doNotIncludeExpiredFields
003ca729 417 * Should only fields where today's date falls within the valid range be returned?
2a6da8d7 418 *
a6c01b45 419 * @return array
003ca729 420 * Array consisting of field details
6a488035 421 */
e5467560 422 public static function getSetDetail($setID, $required = TRUE, $doNotIncludeExpiredFields = FALSE) {
6a488035 423 // create a new tree
be2fb01f 424 $setTree = [];
6a488035 425
be2fb01f 426 $priceFields = [
6a488035
TO
427 'id',
428 'name',
429 'label',
430 'html_type',
431 'is_enter_qty',
432 'help_pre',
433 'help_post',
434 'weight',
435 'is_display_amounts',
436 'options_per_line',
437 'is_active',
438 'active_on',
439 'expire_on',
440 'javascript',
441 'visibility_id',
442 'is_required',
be2fb01f 443 ];
6a488035
TO
444 if ($required == TRUE) {
445 $priceFields[] = 'is_required';
446 }
447
448 // create select
449 $select = 'SELECT ' . implode(',', $priceFields);
450 $from = ' FROM civicrm_price_field';
451
be2fb01f
CW
452 $params = [
453 1 => [$setID, 'Integer'],
454 ];
9bb909ef 455 $currentTime = date('YmdHis');
456 $where = "
6a488035
TO
457WHERE price_set_id = %1
458AND is_active = 1
9bb909ef 459";
6a488035 460 $dateSelect = '';
e5467560 461 if ($doNotIncludeExpiredFields) {
6a488035 462 $dateSelect = "
985c84bf 463AND ( active_on IS NULL OR active_on <= {$currentTime} )
6a488035
TO
464AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
465";
466 }
467
468 $orderBy = ' ORDER BY weight';
469
470 $sql = $select . $from . $where . $dateSelect . $orderBy;
471
472 $dao = CRM_Core_DAO::executeQuery($sql, $params);
473
265807d1
PN
474 $isDefaultContributionPriceSet = FALSE;
475 if ('default_contribution_amount' == CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $setID)) {
476 $isDefaultContributionPriceSet = TRUE;
477 }
478
6a488035
TO
479 $visibility = CRM_Core_PseudoConstant::visibility('name');
480 while ($dao->fetch()) {
481 $fieldID = $dao->id;
482
be2fb01f 483 $setTree[$setID]['fields'][$fieldID] = [];
6a488035
TO
484 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
485
486 foreach ($priceFields as $field) {
487 if ($field == 'id' || is_null($dao->$field)) {
488 continue;
489 }
490
491 if ($field == 'visibility_id') {
492 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
493 }
494 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
495 }
265807d1 496 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField::getOptions($fieldID, FALSE, FALSE, $isDefaultContributionPriceSet);
6a488035
TO
497 }
498
499 // also get the pre and post help from this price set
500 $sql = "
601c7a24 501SELECT extends, financial_type_id, help_pre, help_post, is_quick_config, min_amount
6a488035
TO
502FROM civicrm_price_set
503WHERE id = %1";
504 $dao = CRM_Core_DAO::executeQuery($sql, $params);
505 if ($dao->fetch()) {
506 $setTree[$setID]['extends'] = $dao->extends;
157b21d8 507 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id;
6a488035
TO
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;
601c7a24 511 $setTree[$setID]['min_amount'] = $dao->min_amount;
6a488035
TO
512 }
513 return $setTree;
514 }
515
85020e43 516 /**
003ca729
EM
517 * Get the Price Field ID.
518 *
519 * We call this function when more than one being present would represent an error
85020e43
EM
520 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
521 * @param array $priceSet
522 *
523 * @throws CRM_Core_Exception
524 * @return int
525 */
00be9182 526 public static function getOnlyPriceFieldID(array $priceSet) {
22e263ad 527 if (count($priceSet['fields']) > 1) {
1bde39c7 528 throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
85020e43
EM
529 }
530 return (int) implode('_', array_keys($priceSet['fields']));
531 }
532
533 /**
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
537 *
538 * @throws CRM_Core_Exception
539 * @return int
540 */
00be9182 541 public static function getOnlyPriceFieldValueID(array $priceSet) {
85020e43 542 $priceFieldID = self::getOnlyPriceFieldID($priceSet);
22e263ad 543 if (count($priceSet['fields'][$priceFieldID]['options']) > 1) {
1bde39c7 544 throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
85020e43
EM
545 }
546 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
547 }
548
ffd93213 549 /**
003ca729
EM
550 * Initiate price set such that various non-BAO things are set on the form.
551 *
552 * This function is not really a BAO function so the location is misleading.
553 *
e0c1764e 554 * @param CRM_Core_Form $form
003ca729 555 * Form entity id.
ffd93213 556 * @param string $entityTable
e5467560 557 * @param bool $doNotIncludeExpiredFields
100fef9d 558 * @param int $priceSetId
003ca729 559 * Price Set ID
ffd93213 560 */
e5467560 561 public static function initSet(&$form, $entityTable = 'civicrm_event', $doNotIncludeExpiredFields = FALSE, $priceSetId = NULL) {
6a488035 562
1bde39c7 563 //check if price set is is_config
6a488035 564 if (is_numeric($priceSetId)) {
9da8dc8c 565 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
6a488035
TO
566 $form->assign('quickConfig', 1);
567 }
568 }
569 // get price info
570 if ($priceSetId) {
571 if ($form->_action & CRM_Core_Action::UPDATE) {
572 $entityId = $entity = NULL;
573
574 switch ($entityTable) {
575 case 'civicrm_event':
576 $entity = 'participant';
8535cf1c 577 if (in_array(CRM_Utils_System::getClassName($form), ['CRM_Event_Form_Participant', 'CRM_Event_Form_Task_Register'])) {
6a488035
TO
578 $entityId = $form->_id;
579 }
580 else {
581 $entityId = $form->_participantId;
582 }
583 break;
584
585 case 'civicrm_contribution_page':
586 case 'civicrm_contribution':
587 $entity = 'contribution';
588 $entityId = $form->_id;
589 break;
590 }
591
592 if ($entityId && $entity) {
593 $form->_values['line_items'] = CRM_Price_BAO_LineItem::getLineItems($entityId, $entity);
594 }
595 $required = FALSE;
596 }
597 else {
598 $required = TRUE;
599 }
600
601 $form->_priceSetId = $priceSetId;
e5467560 602 $priceSet = self::getSetDetail($priceSetId, $required, $doNotIncludeExpiredFields);
9c1bc317
CW
603 $form->_priceSet = $priceSet[$priceSetId] ?? NULL;
604 $form->_values['fee'] = $form->_priceSet['fields'] ?? NULL;
6a488035
TO
605
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']) {
be2fb01f 611 $optionsCountDetails = [];
6a488035
TO
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);
1bde39c7 616 $optionsCountDetails['fields'][$field['id']]['options'][$option['id']] = $count;
6a488035
TO
617 }
618 }
619 }
1bde39c7 620 $form->_priceSet['optionsCountDetails'] = $optionsCountDetails;
6a488035
TO
621 }
622
623 //get option max value info.
624 $optionsMaxValueTotal = 0;
be2fb01f 625 $optionsMaxValueDetails = [];
6a488035
TO
626
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;
633 }
634 }
635 }
636
637 $form->_priceSet['optionsMaxValueTotal'] = $optionsMaxValueTotal;
638 if ($optionsMaxValueTotal) {
639 $form->_priceSet['optionsMaxValueDetails'] = $optionsMaxValueDetails;
640 }
641 }
642 $form->set('priceSetId', $form->_priceSetId);
643 $form->set('priceSet', $form->_priceSet);
6a488035 644 }
6a488035
TO
645 }
646
ffd93213 647 /**
003ca729
EM
648 * Get line item purchase information.
649 *
650 * This function takes the input parameters and interprets out of it what has been purchased.
651 *
ffd93213 652 * @param $fields
003ca729
EM
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.
c490a46a 656 * @param array $params
003ca729 657 * Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
ffd93213 658 * @param $lineItem
003ca729 659 * Line item array to be altered.
1bde39c7 660 * @param int $priceSetID
ba2bd875 661 *
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.
ffd93213 664 */
bdcbbfea 665 public static function processAmount($fields, &$params, &$lineItem, $priceSetID = NULL) {
6a488035 666 // using price set
dc428161 667 $totalPrice = $totalTax = 0;
6a488035 668 foreach ($fields as $id => $field) {
a7488080 669 if (empty($params["price_{$id}"]) ||
6a488035
TO
670 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
671 ) {
672 // skip if nothing was submitted for this field
673 continue;
674 }
675
e9448587 676 [$params, $lineItem] = self::getLine($params, $lineItem, $priceSetID, $field, $id);
6a488035
TO
677 }
678
be2fb01f 679 $amount_level = [];
6a488035
TO
680 $totalParticipant = 0;
681 if (is_array($lineItem)) {
682 foreach ($lineItem as $values) {
dfdee387 683 $totalPrice += $values['line_total'] + $values['tax_amount'];
684 $totalTax += $values['tax_amount'];
6a488035 685 $totalParticipant += $values['participant_count'];
2b308818
DG
686 // This is a bit nasty. The logic of 'quick config' was because price set configuration was
687 // (and still is) too difficult to replace the 'quick config' price set configuration on the contribution
688 // page.
689 //
690 // However, because the quick config concept existed all sorts of logic was hung off it
691 // and function behaviour sometimes depends on whether 'price set' is set - although actually it
692 // is always set at the functional level. In this case we are dealing with the default 'quick config'
693 // price set having a label of 'Contribution Amount' which could wind up creating a 'funny looking' label.
694 // 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 // place holder.
696 //
697 // But, in the interests of being careful when capacity is low - avoiding the known default value
698 // will get us by.
699 // Crucially a test has been added so a better solution can be implemented later with some comfort.
c039f658 700 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
ba2bd875 701 if ($values['label'] !== ts('Contribution Amount')) {
2b308818
DG
702 $amount_level[] = $values['label'] . ' - ' . (float) $values['qty'];
703 }
6a488035
TO
704 }
705 }
706
707 $displayParticipantCount = '';
708 if ($totalParticipant > 0) {
709 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
710 }
c039f658 711 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
c0214b81 712 if (!empty($amount_level)) {
0aa9b939 713 $params['amount_level'] = CRM_Utils_Array::implodePadded($amount_level);
c0214b81 714 if (!empty($displayParticipantCount)) {
d7a867a8 715 $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
c0214b81 716 }
2b308818 717 }
88afada7 718
719 $params['amount'] = $totalPrice;
dc428161 720 $params['tax_amount'] = $totalTax;
6a488035
TO
721 }
722
c039f658 723 /**
724 * Get the text to record for amount level.
725 *
726 * @param array $params
727 * Submitted parameters
728 * - priceSetId is required to be set in the calling function
729 * (we don't e-notice check it to enforce that - all payments DO have a price set - even if it is the
730 * default one & this function asks that be set if it is the case).
731 *
732 * @return string
733 * Text for civicrm_contribution.amount_level field.
734 */
735 public static function getAmountLevelText($params) {
736 $priceSetID = $params['priceSetId'];
737 $priceFieldSelection = self::filterPriceFieldsFromParams($priceSetID, $params);
738 $priceFieldMetadata = self::getCachedPriceSetDetail($priceSetID);
8c632a5d 739 $displayParticipantCount = NULL;
0f8a0349 740
be2fb01f 741 $amount_level = [];
c039f658 742 foreach ($priceFieldMetadata['fields'] as $field) {
743 if (!empty($priceFieldSelection[$field['id']])) {
0f8a0349 744 $qtyString = '';
c039f658 745 if ($field['is_enter_qty']) {
746 $qtyString = ' - ' . (float) $params['price_' . $field['id']];
747 }
748 // We deliberately & specifically exclude contribution amount as it has a specific meaning.
749 // ie. it represents the default price field for a contribution. Another approach would be not
750 // to give it a label if we don't want it to show.
ba2bd875 751 if ($field['label'] !== ts('Contribution Amount')) {
c039f658 752 $amount_level[] = $field['label'] . $qtyString;
753 }
754 }
755 }
756 return CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
757 }
758
759 /**
760 * Get the fields relevant to the price field from the parameters.
761 *
762 * E.g we are looking for price_5 => 7 out of a big array of input parameters.
763 *
764 * @param int $priceSetID
765 * @param array $params
766 *
767 * @return array
768 * Price fields found in the params array
769 */
770 public static function filterPriceFieldsFromParams($priceSetID, $params) {
771 $priceSet = self::getCachedPriceSetDetail($priceSetID);
be2fb01f 772 $return = [];
c039f658 773 foreach ($priceSet['fields'] as $field) {
774 if (!empty($params['price_' . $field['id']])) {
775 $return[$field['id']] = $params['price_' . $field['id']];
776 }
777 }
778 return $return;
779 }
780
781 /**
782 * Wrapper for getSetDetail with caching.
783 *
784 * We seem to be passing this array around in a painful way - presumably to avoid the hit
785 * of loading it - so lets make it callable with caching.
786 *
787 * Why not just add caching to the other function? We could do - it just seemed a bit unclear the best caching pattern
788 * & the function was already pretty fugly. Also, I feel like we need to migrate the interaction with price-sets into
789 * a more granular interaction - ie. retrieve specific data using specific functions on this class & have the form
790 * think less about the price sets.
791 *
792 * @param int $priceSetID
793 *
794 * @return array
795 */
796 public static function getCachedPriceSetDetail($priceSetID) {
797 $cacheKey = __CLASS__ . __FUNCTION__ . '_' . $priceSetID;
798 $cache = CRM_Utils_Cache::singleton();
982f1e47 799 $values = $cache->get($cacheKey);
c039f658 800 if (empty($values)) {
801 $data = self::getSetDetail($priceSetID);
802 $values = $data[$priceSetID];
803 $cache->set($cacheKey, $values);
804 }
805 return $values;
806 }
807
6a488035 808 /**
100fef9d 809 * Build the price set form.
6a488035 810 *
e0c1764e 811 * @param CRM_Core_Form $form
dd244018 812 *
355ba699 813 * @return void
6a488035 814 */
00be9182 815 public static function buildPriceSet(&$form) {
6a488035 816 $priceSetId = $form->get('priceSetId');
6a488035
TO
817 if (!$priceSetId) {
818 return;
819 }
820
821 $validFieldsOnly = TRUE;
822 $className = CRM_Utils_System::getClassName($form);
be2fb01f 823 if (in_array($className, [
353ffa53 824 'CRM_Contribute_Form_Contribution',
acb1052e 825 'CRM_Member_Form_Membership',
be2fb01f 826 ])) {
6a488035
TO
827 $validFieldsOnly = FALSE;
828 }
829
353ffa53 830 $priceSet = self::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
9c1bc317 831 $form->_priceSet = $priceSet[$priceSetId] ?? NULL;
883e4763 832 $validPriceFieldIds = array_keys($form->_priceSet['fields']);
6a488035 833 $form->_quickConfig = $quickConfig = 0;
9da8dc8c 834 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
6a488035
TO
835 $quickConfig = 1;
836 }
837
838 $form->assign('quickConfig', $quickConfig);
839 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
840 $form->_quickConfig = $quickConfig;
841 }
ee7f71d9
AS
842
843 // Mark which field should have the auto-renew checkbox, if any. CRM-18305
f4fd225b 844 if (!empty($form->_membershipTypeValues) && is_array($form->_membershipTypeValues)) {
be2fb01f 845 $autoRenewMembershipTypes = [];
36601c73
MW
846 foreach ($form->_membershipTypeValues as $membershipTypeValue) {
847 if ($membershipTypeValue['auto_renew']) {
848 $autoRenewMembershipTypes[] = $membershipTypeValue['id'];
ee7f71d9
AS
849 }
850 }
a012055b 851 foreach ($form->_priceSet['fields'] as $field) {
ee7f71d9
AS
852 if (array_key_exists('options', $field) && is_array($field['options'])) {
853 foreach ($field['options'] as $option) {
b3460c23 854 if (!empty($option['membership_type_id'])) {
ee7f71d9
AS
855 if (in_array($option['membership_type_id'], $autoRenewMembershipTypes)) {
856 $form->_priceSet['auto_renew_membership_field'] = $field['id'];
857 // Only one field can offer auto_renew memberships, so break here.
858 break;
859 }
860 }
861 }
862 }
863 }
864 }
a7f41fd0 865 $form->_priceSet['id'] = $form->_priceSet['id'] ?? $priceSetId;
6a488035
TO
866 $form->assign('priceSet', $form->_priceSet);
867
868 $component = 'contribution';
869 if ($className == 'CRM_Member_Form_Membership') {
870 $component = 'membership';
871 }
872
873 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
874 $feeBlock = &$form->_values['fee'];
875 if (!empty($form->_useForMember)) {
876 $component = 'membership';
877 }
878 }
879 else {
880 $feeBlock = &$form->_priceSet['fields'];
881 }
63b45b1d 882
63b45b1d 883 // Call the buildAmount hook.
6a488035
TO
884 CRM_Utils_Hook::buildAmount($component, $form, $feeBlock);
885
e9448587 886 self::addPriceFieldsToForm($form, $feeBlock, $validFieldsOnly, $className, $validPriceFieldIds);
6a488035
TO
887 }
888
889 /**
003ca729
EM
890 * Check the current Membership having end date null.
891 *
892 * @param array $options
893 * @param int $userid
894 * Probably actually contact ID.
895 *
896 * @return bool
6a488035 897 */
00be9182 898 public static function checkCurrentMembership(&$options, $userid) {
6a488035 899 if (!$userid || empty($options)) {
925157c5 900 return FALSE;
6a488035 901 }
be2fb01f 902 static $_contact_memberships = [];
003ca729 903 $checkLifetime = FALSE;
6a488035 904 foreach ($options as $key => $value) {
a7488080 905 if (!empty($value['membership_type_id'])) {
6a488035
TO
906 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
907 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership::getContactMembership($userid, $value['membership_type_id'], FALSE);
908 }
909 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
8cc574cf 910 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
6a488035 911 unset($options[$key]);
003ca729 912 $checkLifetime = TRUE;
6a488035
TO
913 }
914 }
915 }
003ca729 916 if ($checkLifetime) {
6a488035
TO
917 return TRUE;
918 }
919 else {
920 return FALSE;
921 }
922 }
923
924 /**
100fef9d 925 * Set daefult the price set fields.
6a488035 926 *
c490a46a 927 * @param CRM_Core_Form $form
fd31fa4c
EM
928 * @param $defaults
929 *
a6c01b45 930 * @return array
6a488035 931 */
00be9182 932 public static function setDefaultPriceSet(&$form, &$defaults) {
6a488035
TO
933 if (!isset($form->_priceSet) || empty($form->_priceSet['fields'])) {
934 return $defaults;
935 }
936
1bde39c7 937 foreach ($form->_priceSet['fields'] as $val) {
6a488035 938 foreach ($val['options'] as $keys => $values) {
cb063506
KJ
939 // build price field index which is passed via URL
940 // url format will be appended by "&price_5=11"
941 $priceFieldName = 'price_' . $values['price_field_id'];
942 $priceFieldValue = self::getPriceFieldValueFromURL($form, $priceFieldName);
943 if (!empty($priceFieldValue)) {
034b5cb6 944 self::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $defaults);
cb063506
KJ
945 // break here to prevent overwriting of default due to 'is_default'
946 // option configuration. The value sent via URL get's higher priority.
947 break;
948 }
949 elseif ($values['is_default']) {
034b5cb6 950 self::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $defaults);
6a488035
TO
951 }
952 }
953 }
954 return $defaults;
955 }
956
034b5cb6
KJ
957 /**
958 * Get the value of price field if passed via url
959 *
960 * @param string $priceFieldName
961 * @param string $priceFieldValue
962 * @param string $priceFieldType
963 * @param array $defaults
964 *
965 * @return void
966 */
967 public static function setDefaultPriceSetField($priceFieldName, $priceFieldValue, $priceFieldType, &$defaults) {
968 if ($priceFieldType == 'CheckBox') {
969 $defaults[$priceFieldName][$priceFieldValue] = 1;
970 }
971 else {
972 $defaults[$priceFieldName] = $priceFieldValue;
973 }
974 }
975
cb063506
KJ
976 /**
977 * Get the value of price field if passed via url
978 *
979 * @param CRM_Core_Form $form
980 * @param string $priceFieldName
981 *
982 * @return mixed $priceFieldValue
983 */
984 public static function getPriceFieldValueFromURL(&$form, $priceFieldName) {
985 $priceFieldValue = CRM_Utils_Request::retrieve($priceFieldName, 'String', $form, FALSE, NULL, 'GET');
986 if (!empty($priceFieldValue)) {
987 return $priceFieldValue;
988 }
989 }
990
b2cdd843
EM
991 /**
992 * Supports event create function by setting up required price sets, not tested but expect
993 * it will work for contribution page
414c1420
TO
994 * @param array $params
995 * As passed to api/bao create fn.
996 * @param CRM_Core_DAO $entity
997 * Object for given entity.
998 * @param string $entityName
999 * Name of entity - e.g event.
b2cdd843 1000 */
00be9182 1001 public static function setPriceSets(&$params, $entity, $entityName) {
22e263ad 1002 if (empty($params['price_set_id']) || !is_array($params['price_set_id'])) {
b2cdd843
EM
1003 return;
1004 }
1005 // CRM-14069 note that we may as well start by assuming more than one.
1006 // currently the form does not pass in as an array & will be skipped
1007 // test is passing in as an array but I feel the api should have a metadata that allows
1008 // transform of single to array - seems good for managing transitions - in which case all api
1009 // calls that set price_set_id will hit this
1010 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1011 // all separated values, strings, json half-separated values (in participant we hit this)
1012 // to be converted to json @ api layer
1013 $pse = new CRM_Price_DAO_PriceSetEntity();
1014 $pse->entity_table = 'civicrm_' . $entityName;
1015 $pse->entity_id = $entity->id;
1016 while ($pse->fetch()) {
22e263ad 1017 if (!in_array($pse->price_set_id, $params['price_set_id'])) {
b2cdd843
EM
1018 // note an even more aggressive form of this deletion currently happens in event form
1019 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1020 // on the participant record
1021 if (CRM_Price_BAO_PriceSet::removeFrom('civicrm_' . $entityName, $entity->id)) {
ba1dcfda 1022 CRM_Core_BAO_Discount::del($entity->id, 'civicrm_' . $entityName);
b2cdd843
EM
1023 }
1024 }
1025 }
1026 foreach ($params['price_set_id'] as $priceSetID) {
1027 CRM_Price_BAO_PriceSet::addTo('civicrm_' . $entityName, $entity->id, $priceSetID);
1028 //@todo - how should we do this - copied from form
b53cbfbc 1029 //if (!empty($params['price_field_id'])) {
b2cdd843
EM
1030 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1031 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1032 //}
1033 }
1034 }
353ffa53 1035
6a488035 1036 /**
fe482240 1037 * Get field ids of a price set.
6a488035 1038 *
414c1420
TO
1039 * @param int $id
1040 * Price Set id.
6a488035 1041 *
a6c01b45 1042 * @return array
16b10e64 1043 * Array of the field ids
6a488035 1044 *
6a488035
TO
1045 */
1046 public static function getFieldIds($id) {
9da8dc8c 1047 $priceField = new CRM_Price_DAO_PriceField();
6a488035
TO
1048 $priceField->price_set_id = $id;
1049 $priceField->find();
1050 while ($priceField->fetch()) {
1051 $var[] = $priceField->id;
1052 }
1053 return $var;
1054 }
1055
1056 /**
72b3a70c 1057 * Copy a price set, including all the fields
6a488035 1058 *
414c1420
TO
1059 * @param int $id
1060 * The price set id to copy.
6a488035 1061 *
72b3a70c 1062 * @return CRM_Price_DAO_PriceSet
6a488035 1063 */
00be9182 1064 public static function copy($id) {
6a488035 1065 $maxId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
be2fb01f 1066 $priceSet = civicrm_api3('PriceSet', 'getsingle', ['id' => $id]);
d5c9aa02 1067
1068 $newTitle = preg_replace('/\[Copy id \d+\]$/', "", $priceSet['title']);
be2fb01f
CW
1069 $title = ts('[Copy id %1]', [1 => $maxId + 1]);
1070 $fieldsFix = [
1071 'replace' => [
06f258d2 1072 'title' => trim($newTitle) . ' ' . $title,
d5c9aa02 1073 'name' => substr($priceSet['name'], 0, 20) . 'price_set_' . ($maxId + 1),
be2fb01f
CW
1074 ],
1075 ];
6a488035 1076
d5c9aa02 1077 $copy = CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSet',
be2fb01f 1078 ['id' => $id],
353ffa53
TO
1079 NULL,
1080 $fieldsFix
6a488035
TO
1081 );
1082
1083 //copying all the blocks pertaining to the price set
d5c9aa02 1084 $copyPriceField = CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceField',
be2fb01f
CW
1085 ['price_set_id' => $id],
1086 ['price_set_id' => $copy->id]
6a488035
TO
1087 );
1088 if (!empty($copyPriceField)) {
1089 $price = array_combine(self::getFieldIds($id), self::getFieldIds($copy->id));
1090
1091 //copy option group and values
1092 foreach ($price as $originalId => $copyId) {
9da8dc8c 1093 CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceFieldValue',
be2fb01f
CW
1094 ['price_field_id' => $originalId],
1095 ['price_field_id' => $copyId]
6a488035
TO
1096 );
1097 }
1098 }
1099 $copy->save();
1100
1101 CRM_Utils_Hook::copy('Set', $copy);
4f238b49 1102 unset(\Civi::$statics['CRM_Core_PseudoConstant']);
6a488035
TO
1103 return $copy;
1104 }
1105
1106 /**
fe482240 1107 * check price set permission.
6a488035 1108 *
414c1420
TO
1109 * @param int $sid
1110 * The price set id.
77b97be7
EM
1111 *
1112 * @return bool
beb414cc 1113 * @throws \CRM_Core_Exception
6a488035 1114 */
00be9182 1115 public static function checkPermission($sid) {
44c8822b 1116 if ($sid && self::eventPriceSetDomainID()) {
9da8dc8c 1117 $domain_id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
6a488035 1118 if (CRM_Core_Config::domainID() != $domain_id) {
beb414cc 1119 CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
6a488035
TO
1120 }
1121 }
1122 return TRUE;
1123 }
1124
1125 /**
1126 * Get the sum of participant count
1127 * for all fields of given price set.
1128 *
414c1420
TO
1129 * @param int $sid
1130 * The price set id.
6a488035 1131 *
77b97be7
EM
1132 * @param bool $onlyActive
1133 *
1134 * @return int|null|string
6a488035
TO
1135 */
1136 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1137 $count = 0;
1138 if (!$sid) {
1139 return $count;
1140 }
1141
1142 $where = NULL;
1143 if ($onlyActive) {
1144 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1145 }
1146
be2fb01f 1147 static $pricesetFieldCount = [];
6a488035
TO
1148 if (!isset($pricesetFieldCount[$sid])) {
1149 $sql = "
1150 SELECT sum(value.count) as totalCount
1151 FROM civicrm_price_field_value value
1152INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1153INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1154 WHERE pset.id = %1
1155 $where";
1156
be2fb01f 1157 $count = CRM_Core_DAO::singleValueQuery($sql, [1 => [$sid, 'Positive']]);
6a488035
TO
1158 $pricesetFieldCount[$sid] = ($count) ? $count : 0;
1159 }
1160
1161 return $pricesetFieldCount[$sid];
1162 }
1163
ffd93213 1164 /**
8eacd522
MW
1165 * Return a count of priceFieldValueIDs that are memberships by organisation and membership type
1166 *
1167 * @param string $priceFieldValueIDs
1168 * Comma separated string of priceFieldValue IDs
ffd93213
EM
1169 *
1170 * @return array
8eacd522 1171 * Returns an array of counts by membership organisation
ffd93213 1172 */
8eacd522 1173 public static function getMembershipCount($priceFieldValueIDs) {
6a488035 1174 $queryString = "
2dc536ec 1175SELECT count( pfv.id ) AS count, mt.member_of_contact_id AS id
6a488035
TO
1176FROM civicrm_price_field_value pfv
1177INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
8eacd522 1178WHERE pfv.id IN ( $priceFieldValueIDs )
2dc536ec 1179GROUP BY mt.member_of_contact_id ";
6a488035
TO
1180
1181 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
be2fb01f 1182 $count = [];
6a488035
TO
1183
1184 while ($crmDAO->fetch()) {
1185 $count[$crmDAO->id] = $crmDAO->count;
1186 }
1187
1188 return $count;
1189 }
1190
1191 /**
fe482240 1192 * Check if auto renew option should be shown.
6a488035 1193 *
8eb1503b 1194 * The auto-renew option should be visible if membership types associated with all the fields has
1195 * been set for auto-renew option.
1196 *
1197 * Auto renew checkbox should be frozen if for all the membership type auto renew is required
1198 *
414c1420
TO
1199 * @param int $priceSetId
1200 * Price set id.
6a488035 1201 *
a6c01b45
CW
1202 * @return int
1203 * $autoRenewOption ( 0:hide, 1:optional 2:required )
6a488035
TO
1204 */
1205 public static function checkAutoRenewForPriceSet($priceSetId) {
8eb1503b 1206 $query = 'SELECT DISTINCT mt.auto_renew, mt.duration_interval, mt.duration_unit,
1207 pf.html_type, pf.id as price_field_id
6a488035
TO
1208 FROM civicrm_price_field_value pfv
1209 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1210 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1211 WHERE pf.price_set_id = %1
1212 AND pf.is_active = 1
8eb1503b 1213 AND pfv.is_active = 1
1214 ORDER BY price_field_id';
6a488035 1215
be2fb01f 1216 $params = [1 => [$priceSetId, 'Integer']];
6a488035 1217
353ffa53 1218 $dao = CRM_Core_DAO::executeQuery($query, $params);
8eb1503b 1219
88089d21 1220 //CRM-18050: Check count of price set fields which has been set with auto-renew option.
137d1fac
WA
1221 //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.
1222 if ($dao->N == 0) {
1223 return 0;
1224 }
1225
6a488035 1226 $autoRenewOption = 2;
be2fb01f 1227 $priceFields = [];
6a488035
TO
1228 while ($dao->fetch()) {
1229 if (!$dao->auto_renew) {
8eb1503b 1230 // If any one can't be renewed none can.
1231 return 0;
6a488035
TO
1232 }
1233 if ($dao->auto_renew == 1) {
1234 $autoRenewOption = 1;
1235 }
1236
8eb1503b 1237 if ($dao->html_type == 'Checkbox' && !in_array($dao->duration_interval . $dao->duration_unit, $priceFields[$dao->price_field_id])) {
1238 // Checkbox fields cannot support auto-renew if they have more than one duration configuration
1239 // as more than one can be selected. Radio and select are either-or so they can have more than one duration.
1240 return 0;
1241 }
1242 $priceFields[$dao->price_field_id][] = $dao->duration_interval . $dao->duration_unit;
1243 foreach ($priceFields as $priceFieldID => $durations) {
1244 if ($priceFieldID != $dao->price_field_id && !in_array($dao->duration_interval . $dao->duration_unit, $durations)) {
1245 // Another price field has a duration configuration that differs so we can't offer auto-renew.
1246 return 0;
1247 }
1248 }
6a488035
TO
1249 }
1250
8eb1503b 1251 return $autoRenewOption;
6a488035
TO
1252 }
1253
1254 /**
fe482240 1255 * Retrieve auto renew frequency and interval.
6a488035 1256 *
414c1420
TO
1257 * @param int $priceSetId
1258 * Price set id.
6a488035 1259 *
a6c01b45
CW
1260 * @return array
1261 * associate array of frequency interval and unit
6a488035
TO
1262 */
1263 public static function getRecurDetails($priceSetId) {
1264 $query = 'SELECT mt.duration_interval, mt.duration_unit
1265 FROM civicrm_price_field_value pfv
1266 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1267 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1268 WHERE pf.price_set_id = %1 LIMIT 1';
1269
be2fb01f 1270 $params = [1 => [$priceSetId, 'Integer']];
6a488035
TO
1271 $dao = CRM_Core_DAO::executeQuery($query, $params);
1272 $dao->fetch();
be2fb01f 1273 return [$dao->duration_interval, $dao->duration_unit];
6a488035
TO
1274 }
1275
ffd93213
EM
1276 /**
1277 * @return object
1278 */
00be9182 1279 public static function eventPriceSetDomainID() {
d356cdeb 1280 return Civi::settings()->get('event_price_set_domain_id');
6a488035
TO
1281 }
1282
1283 /**
fe482240 1284 * Update the is_quick_config flag in the db.
6a488035 1285 *
414c1420
TO
1286 * @param int $id
1287 * Id of the database record.
acb1052e 1288 * @param bool $isQuickConfig we want to set the is_quick_config field.
414c1420 1289 * Value we want to set the is_quick_config field.
6a488035 1290 *
8a4fede3 1291 * @return bool
1292 * true if we found and updated the object, else false
6a488035 1293 */
00be9182 1294 public static function setIsQuickConfig($id, $isQuickConfig) {
9da8dc8c 1295 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
6a488035
TO
1296 }
1297
1298 /**
f72e6e2c 1299 * Check if price set id provides option for user to select both auto-renew and non-auto-renew memberships
6a488035 1300 *
003ca729
EM
1301 * @param int $id
1302 *
1303 * @return bool
6a488035 1304 */
f72e6e2c
EM
1305 public static function isMembershipPriceSetContainsMixOfRenewNonRenew($id) {
1306 $membershipTypes = self::getMembershipTypesFromPriceSet($id);
1307 if (!empty($membershipTypes['autorenew']) && !empty($membershipTypes['non_renew'])) {
1308 return TRUE;
6a488035 1309 }
ba1dcfda 1310 return FALSE;
6a488035
TO
1311 }
1312
37b11065
EM
1313 /**
1314 * Get an array of the membership types in a price set.
1315 *
1316 * @param int $id
1317 *
1318 * @return array(
1319 * Membership types in the price set
1320 */
1321 public static function getMembershipTypesFromPriceSet($id) {
1322 $query
1323 = "SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1324FROM civicrm_price_field_value pfv
1325LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1326LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1327LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1328WHERE ps.id = %1
1329";
1330
be2fb01f 1331 $params = [1 => [$id, 'Integer']];
37b11065
EM
1332 $dao = CRM_Core_DAO::executeQuery($query, $params);
1333
be2fb01f
CW
1334 $membershipTypes = [
1335 'all' => [],
1336 'autorenew' => [],
1337 'autorenew_required' => [],
1338 'autorenew_optional' => [],
1339 ];
37b11065
EM
1340 while ($dao->fetch()) {
1341 if (empty($dao->membership_type_id)) {
1342 continue;
1343 }
1344 $membershipTypes['all'][] = $dao->membership_type_id;
1345 if (!empty($dao->auto_renew)) {
1346 $membershipTypes['autorenew'][] = $dao->membership_type_id;
1347 if ($dao->auto_renew == 2) {
1348 $membershipTypes['autorenew_required'][] = $dao->membership_type_id;
1349 }
1350 else {
1351 $membershipTypes['autorenew_optional'][] = $dao->membership_type_id;
1352 }
1353 }
1354 else {
1355 $membershipTypes['non_renew'][] = $dao->membership_type_id;
1356 }
1357 }
1358 return $membershipTypes;
1359 }
1360
e0c1764e 1361 /**
c6914066
PN
1362 * Copy priceSet when event/contibution page is copied
1363 *
414c1420
TO
1364 * @param string $baoName
1365 * BAO name.
1366 * @param int $id
1367 * Old event/contribution page id.
1368 * @param int $newId
1369 * Newly created event/contribution page id.
c6914066 1370 */
00be9182 1371 public static function copyPriceSet($baoName, $id, $newId) {
9da8dc8c 1372 $priceSetId = CRM_Price_BAO_PriceSet::getFor($baoName, $id);
c6914066 1373 if ($priceSetId) {
9da8dc8c 1374 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
22e263ad 1375 if ($isQuickConfig) {
37326fa1 1376 $copyPriceSet = CRM_Price_BAO_PriceSet::copy($priceSetId);
9da8dc8c 1377 CRM_Price_BAO_PriceSet::addTo($baoName, $newId, $copyPriceSet->id);
44c8822b 1378 }
c6914066 1379 else {
3fec1adc 1380 $copyPriceSet = CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSetEntity',
be2fb01f 1381 [
c6914066
PN
1382 'entity_id' => $id,
1383 'entity_table' => $baoName,
be2fb01f
CW
1384 ],
1385 ['entity_id' => $newId]
c6914066
PN
1386 );
1387 }
1388 // copy event discount
1389 if ($baoName == 'civicrm_event') {
1390 $discount = CRM_Core_BAO_Discount::getOptionGroup($id, 'civicrm_event');
1391 foreach ($discount as $discountId => $setId) {
1392
9da8dc8c 1393 $copyPriceSet = &CRM_Price_BAO_PriceSet::copy($setId);
44c8822b 1394
28156120 1395 CRM_Core_DAO::copyGeneric(
c6914066 1396 'CRM_Core_DAO_Discount',
be2fb01f 1397 [
c6914066 1398 'id' => $discountId,
be2fb01f
CW
1399 ],
1400 [
c6914066
PN
1401 'entity_id' => $newId,
1402 'price_set_id' => $copyPriceSet->id,
be2fb01f 1403 ]
c6914066
PN
1404 );
1405 }
1406 }
1407 }
1408 }
dc428161 1409
d424ffde 1410 /**
fe482240 1411 * Function to set tax_amount and tax_rate in LineItem.
d424ffde
CW
1412 *
1413 * @param array $field
1414 * @param array $lineItem
1415 * @param int $optionValueId
83e1baa3 1416 * @param float $totalTax
d424ffde
CW
1417 *
1418 * @return array
dc428161 1419 */
83e1baa3 1420 public static function setLineItem($field, $lineItem, $optionValueId, &$totalTax) {
4f5911bb 1421 // Here we round - i.e. after multiplying by quantity
dc428161 1422 if ($field['html_type'] == 'Text') {
4706ed3b 1423 $taxAmount = round($field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'], 2);
dc428161 1424 }
1425 else {
4706ed3b 1426 $taxAmount = round($field['options'][$optionValueId]['tax_amount'], 2);
dc428161 1427 }
1428 $taxRate = $field['options'][$optionValueId]['tax_rate'];
dc428161 1429 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1430 $lineItem[$optionValueId]['tax_rate'] = $taxRate;
83e1baa3 1431 $totalTax += $taxAmount;
dc428161 1432 return $lineItem;
1433 }
96025800 1434
362bd1b7 1435 /**
1436 * Get the first price set value IDs from a parameters array.
1437 *
1438 * In practice this is really used when we only expect one to exist.
1439 *
1440 * @param array $params
1441 *
1442 * @return array
1443 * Array of the ids of the price set values.
1444 */
1445 public static function parseFirstPriceSetValueIDFromParams($params) {
1446 $priceSetValueIDs = self::parsePriceSetValueIDsFromParams($params);
1447 return reset($priceSetValueIDs);
1448 }
1449
1450 /**
1451 * Get the price set value IDs from a set of parameters
1452 *
1453 * @param array $params
1454 *
1455 * @return array
1456 * Array of the ids of the price set values.
1457 */
1458 public static function parsePriceSetValueIDsFromParams($params) {
1459 $priceSetParams = self::parsePriceSetArrayFromParams($params);
be2fb01f 1460 $priceSetValueIDs = [];
362bd1b7 1461 foreach ($priceSetParams as $priceSetParam) {
1462 foreach (array_keys($priceSetParam) as $priceValueID) {
1463 $priceSetValueIDs[] = $priceValueID;
1464 }
1465 }
1466 return $priceSetValueIDs;
1467 }
1468
1469 /**
1470 * Get the price set value IDs from a set of parameters
1471 *
1472 * @param array $params
1473 *
1474 * @return array
1475 * Array of price fields filtered from the params.
1476 */
1477 public static function parsePriceSetArrayFromParams($params) {
be2fb01f 1478 $priceSetParams = [];
362bd1b7 1479 foreach ($params as $field => $value) {
1480 $parts = explode('_', $field);
0b34e9a4 1481 if (count($parts) == 2 && $parts[0] == 'price' && is_numeric($parts[1]) && is_array($value)) {
362bd1b7 1482 $priceSetParams[$field] = $value;
1483 }
1484 }
1485 return $priceSetParams;
1486 }
1487
05465712 1488 /**
1489 * Get non-deductible amount from price options
1490 *
1491 * @param int $priceSetId
1492 * @param array $lineItem
1493 *
1494 * @return int
1495 * calculated non-deductible amount.
1496 */
1497 public static function getNonDeductibleAmountFromPriceSet($priceSetId, $lineItem) {
1498 $nonDeductibleAmount = 0;
1499 if (!empty($lineItem[$priceSetId])) {
1bde39c7 1500 foreach ($lineItem[$priceSetId] as $options) {
05465712 1501 $nonDeductibleAmount += $options['non_deductible_amount'] * $options['qty'];
1502 }
1503 }
1504
1505 return $nonDeductibleAmount;
1506 }
1507
f5b8da4b 1508 /**
1509 * Get an array of all forms using a given price set.
1510 *
1511 * @param int $id
1512 *
1513 * @return array
1514 * Pages using the price set, keyed by type. e.g
1515 * array('
1516 * 'civicrm_contribution_page' => array(2,5,6),
1517 * 'civicrm_event' => array(5,6),
1518 * 'civicrm_event_template' => array(7),
1519 * )
1520 */
1521 public static function getFormsUsingPriceSet($id) {
be2fb01f 1522 $forms = [];
f5b8da4b 1523 $queryString = "
1524SELECT entity_table, entity_id
1525FROM civicrm_price_set_entity
1526WHERE price_set_id = %1";
be2fb01f 1527 $params = [1 => [$id, 'Integer']];
f5b8da4b 1528 $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
1529
1530 while ($crmFormDAO->fetch()) {
1531 $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
1532 }
1533 return $forms;
1534 }
1535
1536 /**
1537 * @param array $forms
1538 * Array of forms that use a price set keyed by entity. e.g
1539 * array('
1540 * 'civicrm_contribution_page' => array(2,5,6),
1541 * 'civicrm_event' => array(5,6),
1542 * 'civicrm_event_template' => array(7),
1543 * )
1544 *
1545 * @return mixed
1546 * Array of entities suppliemented with per entity information.
1547 * e.g
1548 * array('civicrm_event' => array(7 => array('title' => 'x'...))
1549 *
1550 * @throws \Exception
1551 */
1552 protected static function reformatUsedByFormsWithEntityData($forms) {
be2fb01f 1553 $usedBy = [];
f5b8da4b 1554 foreach ($forms as $table => $entities) {
1555 switch ($table) {
1556 case 'civicrm_event':
1557 $ids = implode(',', $entities);
1558 $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
1559FROM civicrm_event ce
1560LEFT JOIN civicrm_option_value ON
1561 ( ce.event_type_id = civicrm_option_value.value )
1562LEFT JOIN civicrm_option_group ON
1563 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
1564WHERE
1565 civicrm_option_group.name = 'event_type' AND
1566 ce.id IN ($ids) AND
1567 ce.is_active = 1;";
1568 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
1569 while ($crmDAO->fetch()) {
1570 if ($crmDAO->isTemplate) {
1571 $usedBy['civicrm_event_template'][$crmDAO->id]['title'] = $crmDAO->templateTitle;
1572 $usedBy['civicrm_event_template'][$crmDAO->id]['eventType'] = $crmDAO->eventType;
1573 $usedBy['civicrm_event_template'][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
1574 }
1575 else {
1576 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
1577 $usedBy[$table][$crmDAO->id]['eventType'] = $crmDAO->eventType;
1578 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
1579 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
1580 $usedBy[$table][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
1581 }
1582 }
1583 break;
1584
1585 case 'civicrm_contribution_page':
1586 $ids = implode(',', $entities);
1587 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
1588FROM civicrm_contribution_page cp, civicrm_financial_type ct
1589WHERE ct.id = cp.financial_type_id AND
1590 cp.id IN ($ids) AND
1591 cp.is_active = 1;";
1592 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
1593 while ($crmDAO->fetch()) {
1594 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
1595 $usedBy[$table][$crmDAO->id]['type'] = $crmDAO->type;
1596 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
1597 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
1598 }
1599 break;
1600
1601 case 'civicrm_contribution':
1602 case 'civicrm_membership':
1603 case 'civicrm_participant':
1604 $usedBy[$table] = 1;
1605 break;
1606
1607 default:
ba968e38 1608 throw new CRM_Core_Exception("$table is not supported in PriceSet::usedBy()");
1609
f5b8da4b 1610 }
1611 }
1612 return $usedBy;
1613 }
1614
dcf7cb45 1615 /**
1616 * Get the relevant line item.
1617 *
1618 * Note this is part of code being cleaned up / refactored & may change.
1619 *
1620 * @param array $params
1621 * @param array $lineItem
1622 * @param int $priceSetID
1623 * @param array $field
1624 * @param int $id
dcf7cb45 1625 *
1626 * @return array
1627 */
737bd87c 1628 public static function getLine(&$params, &$lineItem, $priceSetID, $field, $id): array {
dcf7cb45 1629 $totalTax = 0;
1630 switch ($field['html_type']) {
1631 case 'Text':
1632 $firstOption = reset($field['options']);
1633 $params["price_{$id}"] = [$firstOption['id'] => $params["price_{$id}"]];
2602eee5 1634 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
dcf7cb45 1635 $optionValueId = key($field['options']);
1636
1637 if (CRM_Utils_Array::value('name', $field['options'][$optionValueId]) === 'contribution_amount') {
1638 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
1639 if (array_key_exists($params['financial_type_id'], $taxRates)) {
1640 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
1641 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($field['options'][$optionValueId]['amount'], $field['options'][$optionValueId]['tax_rate']);
4706ed3b 1642 $field['options'][$optionValueId]['tax_amount'] = round($taxAmount['tax_amount'], 2);
dcf7cb45 1643 }
1644 }
1645 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
1646 $lineItem = self::setLineItem($field, $lineItem, $optionValueId, $totalTax);
1647 }
dcf7cb45 1648 break;
1649
1650 case 'Radio':
1651 //special case if user select -none-
1652 if ($params["price_{$id}"] <= 0) {
1653 break;
1654 }
1655 $params["price_{$id}"] = [$params["price_{$id}"] => 1];
1656 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
1657
1658 // CRM-18701 Sometimes the amount in the price set is overridden by the amount on the form.
1659 // This is notably the case with memberships and we need to put this amount
1660 // on the line item rather than the calculated amount.
1661 // This seems to only affect radio link items as that is the use case for the 'quick config'
1662 // set up (which allows a free form field).
1663 // @todo $priceSetID is a pseudoparam for permit override - we should stop passing it where we
1664 // don't specifically need it & find a better way where we do.
1665 $amount_override = NULL;
1666
1667 if ($priceSetID && count(self::filterPriceFieldsFromParams($priceSetID, $params)) === 1) {
2602eee5 1668 $amount_override = CRM_Utils_Array::value('total_amount', $params);
dcf7cb45 1669 }
1670 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem, $amount_override);
1671 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
1672 $lineItem = self::setLineItem($field, $lineItem, $optionValueId, $totalTax);
1673 if ($amount_override) {
1674 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
1675 }
1676 }
dcf7cb45 1677 break;
1678
1679 case 'Select':
1680 $params["price_{$id}"] = [$params["price_{$id}"] => 1];
1681 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
1682
2602eee5 1683 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
dcf7cb45 1684 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
1685 $lineItem = self::setLineItem($field, $lineItem, $optionValueId, $totalTax);
1686 }
dcf7cb45 1687 break;
1688
1689 case 'CheckBox':
1690
2602eee5 1691 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
dcf7cb45 1692 foreach ($params["price_{$id}"] as $optionId => $option) {
1693 if (!empty($field['options'][$optionId]['tax_rate'])) {
1694 $lineItem = self::setLineItem($field, $lineItem, $optionId, $totalTax);
1695 }
dcf7cb45 1696 }
1697 break;
1698 }
dfdee387 1699 return [$params, $lineItem];
dcf7cb45 1700 }
1701
e9448587 1702 /**
1703 * Add the relevant price fields to the form.
1704 *
1705 * @param \CRM_Core_Form $form
1706 * @param array $feeBlock
1707 * @param bool $validFieldsOnly
1708 * @param string $className
1709 * @param array $validPriceFieldIds
1710 */
1711 protected static function addPriceFieldsToForm(CRM_Core_Form $form, $feeBlock, bool $validFieldsOnly, string $className, array $validPriceFieldIds) {
1712 $hideAdminValues = !CRM_Core_Permission::check('edit contributions');
1713 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
1714 $adminFieldVisible = CRM_Core_Permission::check('administer CiviCRM');
1715 foreach ($feeBlock as $id => $field) {
1716 if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
1717 (CRM_Utils_Array::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
1718 !$validFieldsOnly
1719 ) {
1720 $options = $field['options'] ?? NULL;
1721 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
1722 $userid = $form->getVar('_membershipContactID');
1723 $checklifetime = self::checkCurrentMembership($options, $userid);
1724 if ($checklifetime) {
1725 $form->assign('ispricelifetime', TRUE);
1726 }
1727 }
1728
1729 $formClasses = ['CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'];
1730
1731 if (!is_array($options) || !in_array($id, $validPriceFieldIds)) {
1732 continue;
1733 }
1734 elseif ($hideAdminValues && !in_array($className, $formClasses)) {
1735 foreach ($options as $key => $currentOption) {
1736 if ($currentOption['visibility_id'] == CRM_Price_BAO_PriceField::getVisibilityOptionID('admin')) {
1737 unset($options[$key]);
1738 }
1739 }
1740 }
1741 if (!empty($options)) {
1742 CRM_Price_BAO_PriceField::addQuickFormElement($form,
1743 'price_' . $field['id'],
1744 $field['id'],
1745 FALSE,
1746 CRM_Utils_Array::value('is_required', $field, FALSE),
1747 NULL,
1748 $options
1749 );
1750 }
1751 }
1752 }
1753 }
1754
6a488035 1755}