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