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