3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2016
37 * Business object for managing price sets
40 class CRM_Price_BAO_PriceSet
extends CRM_Price_DAO_PriceSet
{
43 * Static field for default price set details.
47 static $_defaultPriceSet = NULL;
52 public function __construct() {
53 parent
::__construct();
57 * Takes an associative array and creates a price set object.
59 * @param array $params
60 * (reference) an assoc array of name/value pairs.
62 * @return CRM_Price_DAO_PriceSet
64 public static function create(&$params) {
65 if (empty($params['id']) && empty($params['name'])) {
66 $params['name'] = CRM_Utils_String
::munge($params['title'], '_', 242);
69 $validatePriceSet = TRUE;
70 if (!empty($params['extends']) && is_array($params['extends'])) {
71 if (!array_key_exists(CRM_Core_Component
::getComponentID('CiviEvent'), $params['extends'])
72 ||
!array_key_exists(CRM_Core_Component
::getComponentID('CiviMember'), $params['extends'])
74 $validatePriceSet = FALSE;
76 $params['extends'] = CRM_Utils_Array
::implodePadded($params['extends']);
79 $priceSetID = CRM_Utils_Array
::value('id', $params);
82 if ($validatePriceSet && !empty($params['financial_type_id'])) {
83 CRM_Financial_BAO_FinancialAccount
::validateFinancialType(
84 $params['financial_type_id'],
88 $priceSetBAO = new CRM_Price_BAO_PriceSet();
89 $priceSetBAO->copyValues($params);
90 if (self
::eventPriceSetDomainID()) {
91 $priceSetBAO->domain_id
= CRM_Core_Config
::domainID();
93 return $priceSetBAO->save();
97 * Fetch object based on array of properties.
99 * @param array $params
100 * (reference ) an assoc array of name/value pairs.
101 * @param array $defaults
102 * (reference ) an assoc array to hold the flattened values.
104 * @return CRM_Price_DAO_PriceSet
106 public static function retrieve(&$params, &$defaults) {
107 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
111 * Update the is_active flag in the db.
114 * Id of the database record.
117 * @internal param bool $is_active value we want to set the is_active field
120 * DAO object on success, null otherwise
122 public static function setIsActive($id, $isActive) {
123 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
127 * Calculate the default price set id
128 * assigned to the contribution/membership etc
130 * @param string $entity
136 public static function getDefaultPriceSet($entity = 'contribution') {
137 if (!empty(self
::$_defaultPriceSet[$entity])) {
138 return self
::$_defaultPriceSet[$entity];
140 $entityName = 'default_contribution_amount';
141 if ($entity == 'membership') {
142 $entityName = 'default_membership_type_amount';
146 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
147 FROM civicrm_price_set ps
148 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
149 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
150 WHERE ps.name = '{$entityName}'
153 $dao = CRM_Core_DAO
::executeQuery($sql);
154 self
::$_defaultPriceSet[$entity] = array();
155 while ($dao->fetch()) {
156 self
::$_defaultPriceSet[$entity][$dao->priceFieldValueID
] = array(
157 'setID' => $dao->setID
,
158 'priceFieldID' => $dao->priceFieldID
,
159 'name' => $dao->name
,
160 'label' => $dao->label
,
161 'priceFieldValueID' => $dao->priceFieldValueID
,
162 'membership_type_id' => $dao->membership_type_id
,
163 'amount' => $dao->amount
,
164 'financial_type_id' => $dao->financial_type_id
,
168 return self
::$_defaultPriceSet[$entity];
172 * Get the price set title.
181 public static function getTitle($id) {
182 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
186 * Return a list of all forms which use this price set.
190 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
194 public static function &getUsedBy($id, $simpleReturn = FALSE) {
195 $usedBy = $forms = $tables = array();
197 SELECT entity_table, entity_id
198 FROM civicrm_price_set_entity
199 WHERE price_set_id = %1";
200 $params = array(1 => array($id, 'Integer'));
201 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
203 while ($crmFormDAO->fetch()) {
204 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
205 $tables[] = $crmFormDAO->entity_table
;
207 // Return only tables
208 if ($simpleReturn == 'table') {
213 SELECT cli.entity_table, cli.entity_id
214 FROM civicrm_line_item cli
215 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
216 WHERE cpf.price_set_id = %1";
217 $params = array(1 => array($id, 'Integer'));
218 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
219 while ($crmFormDAO->fetch()) {
220 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
221 $tables[] = $crmFormDAO->entity_table
;
227 // Return only entity data
228 if ($simpleReturn == 'entity') {
231 foreach ($forms as $table => $entities) {
233 case 'civicrm_event':
234 $ids = implode(',', $entities);
235 $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
236 FROM civicrm_event ce
237 LEFT JOIN civicrm_option_value ON
238 ( ce.event_type_id = civicrm_option_value.value )
239 LEFT JOIN civicrm_option_group ON
240 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
242 civicrm_option_group.name = 'event_type' AND
245 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
246 while ($crmDAO->fetch()) {
247 if ($crmDAO->isTemplate
) {
248 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
249 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
250 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
253 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
254 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
255 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
256 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
257 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
262 case 'civicrm_contribution_page':
263 $ids = implode(',', $entities);
264 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
265 FROM civicrm_contribution_page cp, civicrm_financial_type ct
266 WHERE ct.id = cp.financial_type_id AND
269 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
270 while ($crmDAO->fetch()) {
271 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
272 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
273 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
274 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
278 case 'civicrm_contribution':
279 case 'civicrm_membership':
280 case 'civicrm_participant':
285 CRM_Core_Error
::fatal("$table is not supported in PriceSet::usedBy()");
294 * Delete the price set.
300 * false if fields exist for this set, true if the
301 * set could be deleted
304 public static function deleteSet($id) {
305 // remove from all inactive forms
306 $usedBy = self
::getUsedBy($id);
307 if (isset($usedBy['civicrm_event'])) {
308 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
309 $eventDAO = new CRM_Event_DAO_Event();
310 $eventDAO->id
= $eventId;
312 while ($eventDAO->fetch()) {
313 self
::removeFrom('civicrm_event', $eventDAO->id
);
318 // delete price fields
319 $priceField = new CRM_Price_DAO_PriceField();
320 $priceField->price_set_id
= $id;
322 while ($priceField->fetch()) {
323 // delete options first
324 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
327 $set = new CRM_Price_DAO_PriceSet();
329 return $set->delete();
333 * Link the price set with the specified table and id.
335 * @param string $entityTable
336 * @param int $entityId
337 * @param int $priceSetId
341 public static function addTo($entityTable, $entityId, $priceSetId) {
342 // verify that the price set exists
343 $dao = new CRM_Price_DAO_PriceSet();
344 $dao->id
= $priceSetId;
350 $dao = new CRM_Price_DAO_PriceSetEntity();
351 // find if this already exists
352 $dao->entity_id
= $entityId;
353 $dao->entity_table
= $entityTable;
356 // add or update price_set_id
357 $dao->price_set_id
= $priceSetId;
362 * Delete price set for the given entity and id.
364 * @param string $entityTable
365 * @param int $entityId
369 public static function removeFrom($entityTable, $entityId) {
370 $dao = new CRM_Price_DAO_PriceSetEntity();
371 $dao->entity_table
= $entityTable;
372 $dao->entity_id
= $entityId;
373 return $dao->delete();
377 * Find a price_set_id associatied with the given table, id and usedFor
378 * Used For value for events:1, contribution:2, membership:3
380 * @param string $entityTable
381 * @param int $entityId
382 * @param int $usedFor
383 * ( price set that extends/used for particular component ).
385 * @param null $isQuickConfig
386 * @param null $setName
389 * price_set_id, or false if none found
391 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
392 if (!$entityTable ||
!$entityId) {
396 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
397 FROM civicrm_price_set ps
398 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
399 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
400 if ($isQuickConfig) {
401 $sql .= ' AND ps.is_quick_config = 0 ';
404 1 => array($entityTable, 'String'),
405 2 => array($entityId, 'Integer'),
408 $sql .= " AND ps.extends LIKE '%%3%' ";
409 $params[3] = array($usedFor, 'Integer');
412 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
414 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
415 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
419 * Find a price_set_id associated with the given option value or field ID.
421 * @param array $params
422 * (reference) an assoc array of name/value pairs.
423 * array may contain either option id or
427 * price set id on success, null otherwise
429 public static function getSetId(&$params) {
432 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
433 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
434 $fieldValue->id
= $oid;
435 if ($fieldValue->find(TRUE)) {
436 $fid = $fieldValue->price_field_id
;
440 $fid = CRM_Utils_Array
::value('fid', $params);
444 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
451 * Return an associative array of all price sets.
453 * @param bool $withInactive
454 * Whether or not to include inactive entries.
455 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
456 * @param string $column name of the column.
459 * associative array of id => name
461 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE, $column = 'title') {
464 DISTINCT ( price_set_id ) as id, s.{$column}
467 INNER JOIN civicrm_price_field f ON f.price_set_id = s.id
468 INNER JOIN civicrm_price_field_value v ON v.price_field_id = f.id
470 is_quick_config = 0 ";
472 if (!$withInactive) {
473 $query .= ' AND s.is_active = 1 ';
476 if (self
::eventPriceSetDomainID()) {
477 $query .= ' AND s.domain_id = ' . CRM_Core_Config
::domainID();
480 $priceSets = array();
482 if ($extendComponentName) {
483 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
487 $query .= " AND s.extends LIKE '%$componentId%' ";
489 // Check permissioned financial types
490 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialType, CRM_Core_Action
::ADD
);
491 if ($financialType) {
492 $types = implode(',', array_keys($financialType));
493 $query .= ' AND s.financial_type_id IN (' . $types . ') AND v.financial_type_id IN (' . $types . ') ';
496 // Do not display any price sets
499 $query .= " GROUP BY s.id";
500 $dao = CRM_Core_DAO
::executeQuery($query);
501 while ($dao->fetch()) {
502 $priceSets[$dao->id
] = $dao->$column;
508 * Get price set details.
510 * An array containing price set details (including price fields) is returned
514 * @param bool $required
515 * Appears to have no effect based on reading the code.
516 * @param bool $validOnly
517 * Should only fields where today's date falls within the valid range be returned?
520 * Array consisting of field details
522 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
526 $priceFields = array(
535 'is_display_amounts',
544 if ($required == TRUE) {
545 $priceFields[] = 'is_required';
549 $select = 'SELECT ' . implode(',', $priceFields);
550 $from = ' FROM civicrm_price_field';
553 $params[1] = array($setID, 'Integer');
555 WHERE price_set_id = %1
560 $currentTime = date('YmdHis');
562 AND ( active_on IS NULL OR active_on <= {$currentTime} )
563 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
567 $orderBy = ' ORDER BY weight';
569 $sql = $select . $from . $where . $dateSelect . $orderBy;
571 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
573 $visibility = CRM_Core_PseudoConstant
::visibility('name');
574 while ($dao->fetch()) {
577 $setTree[$setID]['fields'][$fieldID] = array();
578 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
580 foreach ($priceFields as $field) {
581 if ($field == 'id' ||
is_null($dao->$field)) {
585 if ($field == 'visibility_id') {
586 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
588 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
590 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE);
593 // also get the pre and post help from this price set
595 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
596 FROM civicrm_price_set
598 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
600 $setTree[$setID]['extends'] = $dao->extends;
601 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
602 $setTree[$setID]['help_pre'] = $dao->help_pre
;
603 $setTree[$setID]['help_post'] = $dao->help_post
;
604 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
610 * Get the Price Field ID.
612 * We call this function when more than one being present would represent an error
613 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
614 * @param array $priceSet
616 * @throws CRM_Core_Exception
619 public static function getOnlyPriceFieldID(array $priceSet) {
620 if (count($priceSet['fields']) > 1) {
621 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
623 return (int) implode('_', array_keys($priceSet['fields']));
627 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
628 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
629 * @param array $priceSet
631 * @throws CRM_Core_Exception
634 public static function getOnlyPriceFieldValueID(array $priceSet) {
635 $priceFieldID = self
::getOnlyPriceFieldID($priceSet);
636 if (count($priceSet['fields'][$priceFieldID]['options']) > 1) {
637 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
639 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
644 * Initiate price set such that various non-BAO things are set on the form.
646 * This function is not really a BAO function so the location is misleading.
648 * @param CRM_Core_Form $form
651 * @param string $entityTable
652 * @param bool $validOnly
653 * @param int $priceSetId
656 * @return bool|false|int|null
658 public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
660 $priceSetId = self
::getFor($entityTable, $id);
663 //check if priceset is is_config
664 if (is_numeric($priceSetId)) {
665 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
666 $form->assign('quickConfig', 1);
671 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
672 $entityId = $entity = NULL;
674 switch ($entityTable) {
675 case 'civicrm_event':
676 $entity = 'participant';
677 if (CRM_Utils_System
::getClassName($form) == 'CRM_Event_Form_Participant') {
678 $entityId = $form->_id
;
681 $entityId = $form->_participantId
;
685 case 'civicrm_contribution_page':
686 case 'civicrm_contribution':
687 $entity = 'contribution';
688 $entityId = $form->_id
;
692 if ($entityId && $entity) {
693 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
701 $form->_priceSetId
= $priceSetId;
702 $priceSet = self
::getSetDetail($priceSetId, $required, $validOnly);
703 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
704 $form->_values
['fee'] = CRM_Utils_Array
::value('fields', $form->_priceSet
);
706 //get the price set fields participant count.
707 if ($entityTable == 'civicrm_event') {
708 //get option count info.
709 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
710 if ($form->_priceSet
['optionsCountTotal']) {
711 $optionsCountDeails = array();
712 if (!empty($form->_priceSet
['fields'])) {
713 foreach ($form->_priceSet
['fields'] as $field) {
714 foreach ($field['options'] as $option) {
715 $count = CRM_Utils_Array
::value('count', $option, 0);
716 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
720 $form->_priceSet
['optionsCountDetails'] = $optionsCountDeails;
723 //get option max value info.
724 $optionsMaxValueTotal = 0;
725 $optionsMaxValueDetails = array();
727 if (!empty($form->_priceSet
['fields'])) {
728 foreach ($form->_priceSet
['fields'] as $field) {
729 foreach ($field['options'] as $option) {
730 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
731 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
732 $optionsMaxValueTotal +
= $maxVal;
737 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
738 if ($optionsMaxValueTotal) {
739 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
742 $form->set('priceSetId', $form->_priceSetId
);
743 $form->set('priceSet', $form->_priceSet
);
751 * Get line item purchase information.
753 * This function takes the input parameters and interprets out of it what has been purchased.
756 * This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
757 * And, it would make sense to introduce caching into that function and call it from here rather than
758 * require the $fields array which is passed from pillar to post around the form in order to pass it in here.
759 * @param array $params
760 * Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
762 * Line item array to be altered.
763 * @param string $component
764 * This parameter appears to only be relevant to determining whether memberships should be auto-renewed.
765 * (and is effectively a boolean for 'is_membership' which could be calculated from the line items.)
767 public static function processAmount($fields, &$params, &$lineItem, $component = '', $priceSetID = NULL) {
769 $totalPrice = $totalTax = 0;
770 // CRM-18701 Sometimes the amount in the price set is overridden by the amount on the form.
771 // This is notably the case with memberships and we need to put this amount
772 // on the line item rather than the calculated amount.
773 // This seems to only affect radio link items as that is the use case for the 'quick config'
774 // set up (which allows a free form field).
775 $amount_override = NULL;
778 $autoRenew = array();
779 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
782 $priceFields = self
::filterPriceFieldsFromParams($priceSetID, $params);
783 if (count($priceFields) == 1 && !empty($params['total_amount'])) {
784 $amount_override = $params['total_amount'];
787 foreach ($fields as $id => $field) {
788 if (empty($params["price_{$id}"]) ||
789 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
791 // skip if nothing was submitted for this field
795 switch ($field['html_type']) {
797 $firstOption = reset($field['options']);
798 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
799 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
800 if (CRM_Utils_Array
::value('tax_rate', $field['options'][key($field['options'])])) {
801 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
802 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
804 if (CRM_Utils_Array
::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
805 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
806 if (array_key_exists($params['financial_type_id'], $taxRates)) {
807 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
808 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
809 $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
810 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
811 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
814 $totalPrice +
= $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[key($field['options'])]);
818 //special case if user select -none-
819 if ($params["price_{$id}"] <= 0) {
822 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
823 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
825 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, $amount_override);
826 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
827 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
828 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
829 if (CRM_Utils_Array
::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
830 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule
::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
833 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
836 // auto_renew exists and is empty in some workflows, which php treat as a 0
837 // and hence we explicitly check to see if auto_renew is numeric
838 isset($lineItem[$optionValueId]['auto_renew']) &&
839 is_numeric($lineItem[$optionValueId]['auto_renew'])
841 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
846 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
847 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
849 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
850 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
851 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
852 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
854 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
857 isset($lineItem[$optionValueId]['auto_renew']) &&
858 is_numeric($lineItem[$optionValueId]['auto_renew'])
860 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
866 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
867 foreach ($params["price_{$id}"] as $optionId => $option) {
868 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionId])) {
869 $lineItem = self
::setLineItem($field, $lineItem, $optionId);
870 $totalTax +
= $field['options'][$optionId]['tax_amount'];
872 $totalPrice +
= $lineItem[$optionId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionId]);
875 isset($lineItem[$optionId]['auto_renew']) &&
876 is_numeric($lineItem[$optionId]['auto_renew'])
878 $autoRenew[$lineItem[$optionId]['auto_renew']] +
= $lineItem[$optionId]['line_total'];
885 $amount_level = array();
886 $totalParticipant = 0;
887 if (is_array($lineItem)) {
888 foreach ($lineItem as $values) {
889 $totalParticipant +
= $values['participant_count'];
890 // This is a bit nasty. The logic of 'quick config' was because price set configuration was
891 // (and still is) too difficult to replace the 'quick config' price set configuration on the contribution
894 // However, because the quick config concept existed all sorts of logic was hung off it
895 // and function behaviour sometimes depends on whether 'price set' is set - although actually it
896 // is always set at the functional level. In this case we are dealing with the default 'quick config'
897 // price set having a label of 'Contribution Amount' which could wind up creating a 'funny looking' label.
898 // The correct answer is probably for it to have an empty label in the DB - the label is never shown so it is a
901 // But, in the interests of being careful when capacity is low - avoiding the known default value
903 // Crucially a test has been added so a better solution can be implemented later with some comfort.
904 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
905 if ($values['label'] != ts('Contribution Amount')) {
906 $amount_level[] = $values['label'] . ' - ' . (float) $values['qty'];
911 $displayParticipantCount = '';
912 if ($totalParticipant > 0) {
913 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
915 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
916 if (!empty($amount_level)) {
917 $params['amount_level'] = CRM_Utils_Array
::implodePadded($amount_level);
918 if (!empty($displayParticipantCount)) {
919 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
922 $params['amount'] = CRM_Utils_Money
::format($totalPrice, NULL, NULL, TRUE);
923 $params['tax_amount'] = $totalTax;
925 foreach ($autoRenew as $dontCare => $eachAmount) {
927 unset($autoRenew[$dontCare]);
930 if (count($autoRenew) > 1) {
931 $params['autoRenew'] = $autoRenew;
937 * Get the text to record for amount level.
939 * @param array $params
940 * Submitted parameters
941 * - priceSetId is required to be set in the calling function
942 * (we don't e-notice check it to enforce that - all payments DO have a price set - even if it is the
943 * default one & this function asks that be set if it is the case).
946 * Text for civicrm_contribution.amount_level field.
948 public static function getAmountLevelText($params) {
949 $priceSetID = $params['priceSetId'];
950 $priceFieldSelection = self
::filterPriceFieldsFromParams($priceSetID, $params);
951 $priceFieldMetadata = self
::getCachedPriceSetDetail($priceSetID);
952 $displayParticipantCount = NULL;
954 $amount_level = array();
955 foreach ($priceFieldMetadata['fields'] as $field) {
956 if (!empty($priceFieldSelection[$field['id']])) {
958 if ($field['is_enter_qty']) {
959 $qtyString = ' - ' . (float) $params['price_' . $field['id']];
961 // We deliberately & specifically exclude contribution amount as it has a specific meaning.
962 // ie. it represents the default price field for a contribution. Another approach would be not
963 // to give it a label if we don't want it to show.
964 if ($field['label'] != ts('Contribution Amount')) {
965 $amount_level[] = $field['label'] . $qtyString;
969 return CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
973 * Get the fields relevant to the price field from the parameters.
975 * E.g we are looking for price_5 => 7 out of a big array of input parameters.
977 * @param int $priceSetID
978 * @param array $params
981 * Price fields found in the params array
983 public static function filterPriceFieldsFromParams($priceSetID, $params) {
984 $priceSet = self
::getCachedPriceSetDetail($priceSetID);
986 foreach ($priceSet['fields'] as $field) {
987 if (!empty($params['price_' . $field['id']])) {
988 $return[$field['id']] = $params['price_' . $field['id']];
995 * Wrapper for getSetDetail with caching.
997 * We seem to be passing this array around in a painful way - presumably to avoid the hit
998 * of loading it - so lets make it callable with caching.
1000 * Why not just add caching to the other function? We could do - it just seemed a bit unclear the best caching pattern
1001 * & the function was already pretty fugly. Also, I feel like we need to migrate the interaction with price-sets into
1002 * a more granular interaction - ie. retrieve specific data using specific functions on this class & have the form
1003 * think less about the price sets.
1005 * @param int $priceSetID
1009 public static function getCachedPriceSetDetail($priceSetID) {
1010 $cacheKey = __CLASS__
. __FUNCTION__
. '_' . $priceSetID;
1011 $cache = CRM_Utils_Cache
::singleton();
1012 $values = $cache->get($cacheKey);
1013 if (empty($values)) {
1014 $data = self
::getSetDetail($priceSetID);
1015 $values = $data[$priceSetID];
1016 $cache->set($cacheKey, $values);
1022 * Build the price set form.
1024 * @param CRM_Core_Form $form
1028 public static function buildPriceSet(&$form) {
1029 $priceSetId = $form->get('priceSetId');
1034 $validFieldsOnly = TRUE;
1035 $className = CRM_Utils_System
::getClassName($form);
1036 if (in_array($className, array(
1037 'CRM_Contribute_Form_Contribution',
1038 'CRM_Member_Form_Membership',
1040 $validFieldsOnly = FALSE;
1043 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
1044 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
1045 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
1046 $form->_quickConfig
= $quickConfig = 0;
1047 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
1051 $form->assign('quickConfig', $quickConfig);
1052 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
1053 $form->_quickConfig
= $quickConfig;
1056 // Mark which field should have the auto-renew checkbox, if any. CRM-18305
1057 if (!empty($form->_membershipTypeValues
) && is_array($form->_membershipTypeValues
)) {
1058 $autoRenewMembershipTypes = array();
1059 foreach ($form->_membershipTypeValues
as $membershiptTypeValue) {
1060 if ($membershiptTypeValue['auto_renew']) {
1061 $autoRenewMembershipTypes[] = $membershiptTypeValue['id'];
1064 foreach ($form->_priceSet
['fields'] as &$field) {
1065 if (array_key_exists('options', $field) && is_array($field['options'])) {
1066 foreach ($field['options'] as $option) {
1067 if (!empty($option['membership_type_id'])) {
1068 if (in_array($option['membership_type_id'], $autoRenewMembershipTypes)) {
1069 $form->_priceSet
['auto_renew_membership_field'] = $field['id'];
1070 // Only one field can offer auto_renew memberships, so break here.
1078 $form->assign('priceSet', $form->_priceSet
);
1080 $component = 'contribution';
1081 if ($className == 'CRM_Member_Form_Membership') {
1082 $component = 'membership';
1085 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
1086 $feeBlock = &$form->_values
['fee'];
1087 if (!empty($form->_useForMember
)) {
1088 $component = 'membership';
1092 $feeBlock = &$form->_priceSet
['fields'];
1094 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1095 foreach ($feeBlock as $key => $value) {
1096 foreach ($value['options'] as $k => $options) {
1097 if (!CRM_Core_Permission
::check('add contributions of type ' . CRM_Contribute_PseudoConstant
::financialType($options['financial_type_id']))) {
1098 unset($feeBlock[$key]['options'][$k]);
1101 if (empty($feeBlock[$key]['options'])) {
1102 unset($feeBlock[$key]);
1107 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
1109 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
1110 $adminFieldVisible = FALSE;
1111 if (CRM_Core_Permission
::check('administer CiviCRM')) {
1112 $adminFieldVisible = TRUE;
1115 foreach ($feeBlock as $id => $field) {
1116 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
1117 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
1120 $options = CRM_Utils_Array
::value('options', $field);
1121 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
1122 $userid = $form->getVar('_membershipContactID');
1123 $checklifetime = self
::checkCurrentMembership($options, $userid);
1124 if ($checklifetime) {
1125 $form->assign('ispricelifetime', TRUE);
1128 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
1131 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
1132 'price_' . $field['id'],
1135 CRM_Utils_Array
::value('is_required', $field, FALSE),
1144 * Check the current Membership having end date null.
1146 * @param array $options
1147 * @param int $userid
1148 * Probably actually contact ID.
1152 public static function checkCurrentMembership(&$options, $userid) {
1153 if (!$userid ||
empty($options)) {
1156 static $_contact_memberships = array();
1157 $checkLifetime = FALSE;
1158 foreach ($options as $key => $value) {
1159 if (!empty($value['membership_type_id'])) {
1160 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
1161 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
1163 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
1164 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
1165 unset($options[$key]);
1166 $checkLifetime = TRUE;
1170 if ($checkLifetime) {
1179 * Set daefult the price set fields.
1181 * @param CRM_Core_Form $form
1186 public static function setDefaultPriceSet(&$form, &$defaults) {
1187 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
1191 foreach ($form->_priceSet
['fields'] as $key => $val) {
1192 foreach ($val['options'] as $keys => $values) {
1193 // build price field index which is passed via URL
1194 // url format will be appended by "&price_5=11"
1195 $priceFieldName = 'price_' . $values['price_field_id'];
1196 $priceFieldValue = self
::getPriceFieldValueFromURL($form, $priceFieldName);
1197 if (!empty($priceFieldValue)) {
1198 self
::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $defaults);
1199 // break here to prevent overwriting of default due to 'is_default'
1200 // option configuration. The value sent via URL get's higher priority.
1203 elseif ($values['is_default']) {
1204 self
::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $defaults);
1212 * Get the value of price field if passed via url
1214 * @param string $priceFieldName
1215 * @param string $priceFieldValue
1216 * @param string $priceFieldType
1217 * @param array $defaults
1221 public static function setDefaultPriceSetField($priceFieldName, $priceFieldValue, $priceFieldType, &$defaults) {
1222 if ($priceFieldType == 'CheckBox') {
1223 $defaults[$priceFieldName][$priceFieldValue] = 1;
1226 $defaults[$priceFieldName] = $priceFieldValue;
1231 * Get the value of price field if passed via url
1233 * @param CRM_Core_Form $form
1234 * @param string $priceFieldName
1236 * @return mixed $priceFieldValue
1238 public static function getPriceFieldValueFromURL(&$form, $priceFieldName) {
1239 $priceFieldValue = CRM_Utils_Request
::retrieve($priceFieldName, 'String', $form, FALSE, NULL, 'GET');
1240 if (!empty($priceFieldValue)) {
1241 return $priceFieldValue;
1246 * Supports event create function by setting up required price sets, not tested but expect
1247 * it will work for contribution page
1248 * @param array $params
1249 * As passed to api/bao create fn.
1250 * @param CRM_Core_DAO $entity
1251 * Object for given entity.
1252 * @param string $entityName
1253 * Name of entity - e.g event.
1255 public static function setPriceSets(&$params, $entity, $entityName) {
1256 if (empty($params['price_set_id']) ||
!is_array($params['price_set_id'])) {
1259 // CRM-14069 note that we may as well start by assuming more than one.
1260 // currently the form does not pass in as an array & will be skipped
1261 // test is passing in as an array but I feel the api should have a metadata that allows
1262 // transform of single to array - seems good for managing transitions - in which case all api
1263 // calls that set price_set_id will hit this
1264 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1265 // all separated values, strings, json half-separated values (in participant we hit this)
1266 // to be converted to json @ api layer
1267 $pse = new CRM_Price_DAO_PriceSetEntity();
1268 $pse->entity_table
= 'civicrm_' . $entityName;
1269 $pse->entity_id
= $entity->id
;
1270 while ($pse->fetch()) {
1271 if (!in_array($pse->price_set_id
, $params['price_set_id'])) {
1272 // note an even more aggressive form of this deletion currently happens in event form
1273 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1274 // on the participant record
1275 if (CRM_Price_BAO_PriceSet
::removeFrom('civicrm_' . $entityName, $entity->id
)) {
1276 CRM_Core_BAO_Discount
::del($entity->id
, 'civicrm_' . $entityName);
1280 foreach ($params['price_set_id'] as $priceSetID) {
1281 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $entityName, $entity->id
, $priceSetID);
1282 //@todo - how should we do this - copied from form
1283 //if (!empty($params['price_field_id'])) {
1284 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1285 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1291 * Get field ids of a price set.
1297 * Array of the field ids
1300 public static function getFieldIds($id) {
1301 $priceField = new CRM_Price_DAO_PriceField();
1302 $priceField->price_set_id
= $id;
1303 $priceField->find();
1304 while ($priceField->fetch()) {
1305 $var[] = $priceField->id
;
1311 * Copy a price set, including all the fields
1314 * The price set id to copy.
1316 * @return CRM_Price_DAO_PriceSet
1318 public static function copy($id) {
1319 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1321 $title = ts('[Copy id %1]', array(1 => $maxId +
1));
1324 'title' => ' ' . $title,
1325 'name' => '__Copy_id_' . ($maxId +
1) . '_',
1329 $copy = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1335 //copying all the blocks pertaining to the price set
1336 $copyPriceField = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1337 array('price_set_id' => $id),
1338 array('price_set_id' => $copy->id
)
1340 if (!empty($copyPriceField)) {
1341 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1343 //copy option group and values
1344 foreach ($price as $originalId => $copyId) {
1345 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1346 array('price_field_id' => $originalId),
1347 array('price_field_id' => $copyId)
1353 CRM_Utils_Hook
::copy('Set', $copy);
1358 * check price set permission.
1365 public static function checkPermission($sid) {
1366 if ($sid && self
::eventPriceSetDomainID()) {
1367 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1368 if (CRM_Core_Config
::domainID() != $domain_id) {
1369 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
1376 * Get the sum of participant count
1377 * for all fields of given price set.
1382 * @param bool $onlyActive
1384 * @return int|null|string
1386 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1394 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1397 static $pricesetFieldCount = array();
1398 if (!isset($pricesetFieldCount[$sid])) {
1400 SELECT sum(value.count) as totalCount
1401 FROM civicrm_price_field_value value
1402 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1403 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1407 $count = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1408 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1411 return $pricesetFieldCount[$sid];
1419 public static function getMembershipCount($ids) {
1421 SELECT count( pfv.id ) AS count, pfv.id AS id
1422 FROM civicrm_price_field_value pfv
1423 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1424 WHERE pfv.id IN ( $ids )
1425 GROUP BY mt.member_of_contact_id";
1427 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1430 while ($crmDAO->fetch()) {
1431 $count[$crmDAO->id
] = $crmDAO->count
;
1438 * Check if auto renew option should be shown.
1440 * The auto-renew option should be visible if membership types associated with all the fields has
1441 * been set for auto-renew option.
1443 * Auto renew checkbox should be frozen if for all the membership type auto renew is required
1445 * @param int $priceSetId
1449 * $autoRenewOption ( 0:hide, 1:optional 2:required )
1451 public static function checkAutoRenewForPriceSet($priceSetId) {
1452 $query = 'SELECT DISTINCT mt.auto_renew, mt.duration_interval, mt.duration_unit,
1453 pf.html_type, pf.id as price_field_id
1454 FROM civicrm_price_field_value pfv
1455 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1456 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1457 WHERE pf.price_set_id = %1
1458 AND pf.is_active = 1
1459 AND pfv.is_active = 1
1460 ORDER BY price_field_id';
1462 $params = array(1 => array($priceSetId, 'Integer'));
1464 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1466 //CRM-18050: Check count of price set fields which has been set with auto-renew option.
1467 //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.
1472 $autoRenewOption = 2;
1473 $priceFields = array();
1474 while ($dao->fetch()) {
1475 if (!$dao->auto_renew
) {
1476 // If any one can't be renewed none can.
1479 if ($dao->auto_renew
== 1) {
1480 $autoRenewOption = 1;
1483 if ($dao->html_type
== 'Checkbox' && !in_array($dao->duration_interval
. $dao->duration_unit
, $priceFields[$dao->price_field_id
])) {
1484 // Checkbox fields cannot support auto-renew if they have more than one duration configuration
1485 // as more than one can be selected. Radio and select are either-or so they can have more than one duration.
1488 $priceFields[$dao->price_field_id
][] = $dao->duration_interval
. $dao->duration_unit
;
1489 foreach ($priceFields as $priceFieldID => $durations) {
1490 if ($priceFieldID != $dao->price_field_id
&& !in_array($dao->duration_interval
. $dao->duration_unit
, $durations)) {
1491 // Another price field has a duration configuration that differs so we can't offer auto-renew.
1497 return $autoRenewOption;
1501 * Retrieve auto renew frequency and interval.
1503 * @param int $priceSetId
1507 * associate array of frequency interval and unit
1509 public static function getRecurDetails($priceSetId) {
1510 $query = 'SELECT mt.duration_interval, mt.duration_unit
1511 FROM civicrm_price_field_value pfv
1512 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1513 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1514 WHERE pf.price_set_id = %1 LIMIT 1';
1516 $params = array(1 => array($priceSetId, 'Integer'));
1517 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1519 return array($dao->duration_interval
, $dao->duration_unit
);
1525 public static function eventPriceSetDomainID() {
1526 return Civi
::settings()->get('event_price_set_domain_id');
1530 * Update the is_quick_config flag in the db.
1533 * Id of the database record.
1534 * @param bool $isQuickConfig we want to set the is_quick_config field.
1535 * Value we want to set the is_quick_config field.
1538 * DAO object on success, null otherwise
1540 public static function setIsQuickConfig($id, $isQuickConfig) {
1541 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1545 * Check if price set id provides option for user to select both auto-renew and non-auto-renew memberships
1551 public static function isMembershipPriceSetContainsMixOfRenewNonRenew($id) {
1552 $membershipTypes = self
::getMembershipTypesFromPriceSet($id);
1553 if (!empty($membershipTypes['autorenew']) && !empty($membershipTypes['non_renew'])) {
1560 * Get an array of the membership types in a price set.
1565 * Membership types in the price set
1567 public static function getMembershipTypesFromPriceSet($id) {
1569 = "SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1570 FROM civicrm_price_field_value pfv
1571 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1572 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1573 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1577 $params = array(1 => array($id, 'Integer'));
1578 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1580 $membershipTypes = array(
1582 'autorenew' => array(),
1583 'autorenew_required' => array(),
1584 'autorenew_optional' => array(),
1586 while ($dao->fetch()) {
1587 if (empty($dao->membership_type_id
)) {
1590 $membershipTypes['all'][] = $dao->membership_type_id
;
1591 if (!empty($dao->auto_renew
)) {
1592 $membershipTypes['autorenew'][] = $dao->membership_type_id
;
1593 if ($dao->auto_renew
== 2) {
1594 $membershipTypes['autorenew_required'][] = $dao->membership_type_id
;
1597 $membershipTypes['autorenew_optional'][] = $dao->membership_type_id
;
1601 $membershipTypes['non_renew'][] = $dao->membership_type_id
;
1604 return $membershipTypes;
1608 * Copy priceSet when event/contibution page is copied
1610 * @param string $baoName
1613 * Old event/contribution page id.
1615 * Newly created event/contribution page id.
1617 public static function copyPriceSet($baoName, $id, $newId) {
1618 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1620 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1621 if ($isQuickConfig) {
1622 $copyPriceSet = CRM_Price_BAO_PriceSet
::copy($priceSetId);
1623 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1626 $copyPriceSet = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1629 'entity_table' => $baoName,
1631 array('entity_id' => $newId)
1634 // copy event discount
1635 if ($baoName == 'civicrm_event') {
1636 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1637 foreach ($discount as $discountId => $setId) {
1639 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1641 CRM_Core_DAO
::copyGeneric(
1642 'CRM_Core_DAO_Discount',
1644 'id' => $discountId,
1647 'entity_id' => $newId,
1648 'price_set_id' => $copyPriceSet->id
,
1657 * Function to set tax_amount and tax_rate in LineItem.
1659 * @param array $field
1660 * @param array $lineItem
1661 * @param int $optionValueId
1665 public static function setLineItem($field, $lineItem, $optionValueId) {
1666 if ($field['html_type'] == 'Text') {
1667 $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
1670 $taxAmount = $field['options'][$optionValueId]['tax_amount'];
1672 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1673 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1674 $lineItem[$optionValueId]['tax_rate'] = $taxRate;
1680 * Get the first price set value IDs from a parameters array.
1682 * In practice this is really used when we only expect one to exist.
1684 * @param array $params
1687 * Array of the ids of the price set values.
1689 public static function parseFirstPriceSetValueIDFromParams($params) {
1690 $priceSetValueIDs = self
::parsePriceSetValueIDsFromParams($params);
1691 return reset($priceSetValueIDs);
1695 * Get the price set value IDs from a set of parameters
1697 * @param array $params
1700 * Array of the ids of the price set values.
1702 public static function parsePriceSetValueIDsFromParams($params) {
1703 $priceSetParams = self
::parsePriceSetArrayFromParams($params);
1704 $priceSetValueIDs = array();
1705 foreach ($priceSetParams as $priceSetParam) {
1706 foreach (array_keys($priceSetParam) as $priceValueID) {
1707 $priceSetValueIDs[] = $priceValueID;
1710 return $priceSetValueIDs;
1714 * Get the price set value IDs from a set of parameters
1716 * @param array $params
1719 * Array of price fields filtered from the params.
1721 public static function parsePriceSetArrayFromParams($params) {
1722 $priceSetParams = array();
1723 foreach ($params as $field => $value) {
1724 $parts = explode('_', $field);
1725 if (count($parts) == 2 && $parts[0] == 'price' && is_numeric($parts[1])) {
1726 $priceSetParams[$field] = $value;
1729 return $priceSetParams;