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