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