3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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
48 static $_defaultPriceSet = NULL;
53 public function __construct() {
54 parent
::__construct();
58 * Takes an associative array and creates a price set object
60 * @param array $params
61 * (reference) an assoc array of name/value pairs.
63 * @return CRM_Price_DAO_PriceSet object
66 public static function create(&$params) {
67 if (empty($params['id']) && empty($params['name'])) {
68 $params['name'] = CRM_Utils_String
::munge($params['title'], '_', 242);
70 if (!empty($params['extends']) && is_array($params['extends'])) {
71 $params['extends'] = CRM_Utils_Array
::implodePadded($params['extends']);
73 $priceSetBAO = new CRM_Price_BAO_PriceSet();
74 $priceSetBAO->copyValues($params);
75 if (self
::eventPriceSetDomainID()) {
76 $priceSetBAO->domain_id
= CRM_Core_Config
::domainID();
78 return $priceSetBAO->save();
82 * Fetch object based on array of properties
84 * @param array $params
85 * (reference ) an assoc array of name/value pairs.
86 * @param array $defaults
87 * (reference ) an assoc array to hold the flattened values.
89 * @return CRM_Price_DAO_PriceSet object
92 public static function retrieve(&$params, &$defaults) {
93 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
97 * Update the is_active flag in the db
100 * Id of the database record.
103 * @internal param bool $is_active value we want to set the is_active field
105 * @return Object DAO object on sucess, null otherwise
108 public static function setIsActive($id, $isActive) {
109 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
113 * Calculate the default price set id
114 * assigned to the contribution/membership etc
116 * @param string $entity
118 * @return array $defaultPriceSet default price set
123 public static function getDefaultPriceSet($entity = 'contribution') {
124 if (!empty(self
::$_defaultPriceSet[$entity])) {
125 return self
::$_defaultPriceSet[$entity];
127 $entityName = 'default_contribution_amount';
128 if ($entity == 'membership') {
129 $entityName = 'default_membership_type_amount';
133 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
134 FROM civicrm_price_set ps
135 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
136 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
137 WHERE ps.name = '{$entityName}'
140 $dao = CRM_Core_DAO
::executeQuery($sql);
141 self
::$_defaultPriceSet[$entity] = array();
142 while ($dao->fetch()) {
143 self
::$_defaultPriceSet[$entity][$dao->priceFieldValueID
] = array(
144 'setID' => $dao->setID
,
145 'priceFieldID' => $dao->priceFieldID
,
146 'name' => $dao->name
,
147 'label' => $dao->label
,
148 'priceFieldValueID' => $dao->priceFieldValueID
,
149 'membership_type_id' => $dao->membership_type_id
,
150 'amount' => $dao->amount
,
151 'financial_type_id' => $dao->financial_type_id
,
155 return self
::$_defaultPriceSet[$entity];
159 * Get the price set title.
164 * @return string title
169 public static function getTitle($id) {
170 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
174 * Return a list of all forms which use this price set.
178 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
182 public static function &getUsedBy($id, $simpleReturn = FALSE) {
183 $usedBy = $forms = $tables = array();
185 SELECT entity_table, entity_id
186 FROM civicrm_price_set_entity
187 WHERE price_set_id = %1";
188 $params = array(1 => array($id, 'Integer'));
189 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
191 while ($crmFormDAO->fetch()) {
192 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
193 $tables[] = $crmFormDAO->entity_table
;
195 // Return only tables
196 if ($simpleReturn == 'table') {
201 SELECT cli.entity_table, cli.entity_id
202 FROM civicrm_line_item cli
203 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
204 WHERE cpf.price_set_id = %1";
205 $params = array(1 => array($id, 'Integer'));
206 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
207 while ($crmFormDAO->fetch()) {
208 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
209 $tables[] = $crmFormDAO->entity_table
;
215 // Return only entity data
216 if ($simpleReturn == 'entity') {
219 foreach ($forms as $table => $entities) {
221 case 'civicrm_event':
222 $ids = implode(',', $entities);
223 $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
224 FROM civicrm_event ce
225 LEFT JOIN civicrm_option_value ON
226 ( ce.event_type_id = civicrm_option_value.value )
227 LEFT JOIN civicrm_option_group ON
228 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
230 civicrm_option_group.name = 'event_type' AND
233 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
234 while ($crmDAO->fetch()) {
235 if ($crmDAO->isTemplate
) {
236 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
237 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
238 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
241 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
242 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
243 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
244 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
245 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
250 case 'civicrm_contribution_page':
251 $ids = implode(',', $entities);
252 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
253 FROM civicrm_contribution_page cp, civicrm_financial_type ct
254 WHERE ct.id = cp.financial_type_id AND
257 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
258 while ($crmDAO->fetch()) {
259 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
260 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
261 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
262 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
266 case 'civicrm_contribution':
267 case 'civicrm_membership':
268 case 'civicrm_participant':
273 CRM_Core_Error
::fatal("$table is not supported in PriceSet::usedBy()");
282 * Delete the price set
287 * @return boolean false if fields exist for this set, true if the
288 * set could be deleted
292 public static function deleteSet($id) {
293 // remove from all inactive forms
294 $usedBy = self
::getUsedBy($id);
295 if (isset($usedBy['civicrm_event'])) {
296 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
297 $eventDAO = new CRM_Event_DAO_Event();
298 $eventDAO->id
= $eventId;
300 while ($eventDAO->fetch()) {
301 self
::removeFrom('civicrm_event', $eventDAO->id
);
306 // delete price fields
307 $priceField = new CRM_Price_DAO_PriceField();
308 $priceField->price_set_id
= $id;
310 while ($priceField->fetch()) {
311 // delete options first
312 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
315 $set = new CRM_Price_DAO_PriceSet();
317 return $set->delete();
321 * Link the price set with the specified table and id
323 * @param string $entityTable
324 * @param int $entityId
325 * @param int $priceSetId
329 public static function addTo($entityTable, $entityId, $priceSetId) {
330 // verify that the price set exists
331 $dao = new CRM_Price_DAO_PriceSet();
332 $dao->id
= $priceSetId;
338 $dao = new CRM_Price_DAO_PriceSetEntity();
339 // find if this already exists
340 $dao->entity_id
= $entityId;
341 $dao->entity_table
= $entityTable;
344 // add or update price_set_id
345 $dao->price_set_id
= $priceSetId;
350 * Delete price set for the given entity and id
352 * @param string $entityTable
353 * @param int $entityId
357 public static function removeFrom($entityTable, $entityId) {
358 $dao = new CRM_Price_DAO_PriceSetEntity();
359 $dao->entity_table
= $entityTable;
360 $dao->entity_id
= $entityId;
361 return $dao->delete();
365 * Find a price_set_id associatied with the given table, id and usedFor
366 * Used For value for events:1, contribution:2, membership:3
368 * @param string $entityTable
369 * @param int $entityId
370 * @param int $usedFor
371 * ( price set that extends/used for particular component ).
373 * @param null $isQuickConfig
374 * @param null $setName
376 * @return integer|false price_set_id, or false if none found
378 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
379 if (!$entityTable ||
!$entityId) {
383 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
384 FROM civicrm_price_set ps
385 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
386 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
387 if ($isQuickConfig) {
388 $sql .= ' AND ps.is_quick_config = 0 ';
391 1 => array($entityTable, 'String'),
392 2 => array($entityId, 'Integer'),
395 $sql .= " AND ps.extends LIKE '%%3%' ";
396 $params[3] = array($usedFor, 'Integer');
399 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
401 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
402 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
406 * Find a price_set_id associated with the given option value or field ID
408 * @param array $params
409 * (reference) an assoc array of name/value pairs.
410 * array may contain either option id or
413 * @return integer|NULL price set id on success, null otherwise
416 public static function getSetId(&$params) {
419 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
420 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
421 $fieldValue->id
= $oid;
422 if ($fieldValue->find(TRUE)) {
423 $fid = $fieldValue->price_field_id
;
427 $fid = CRM_Utils_Array
::value('fid', $params);
431 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
438 * Return an associative array of all price sets
440 * @param bool $withInactive
441 * Whether or not to include inactive entries.
442 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
444 * @return array associative array of id => name
446 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE) {
449 DISTINCT ( price_set_id ) as id, title
454 civicrm_price_set.id = civicrm_price_field.price_set_id AND is_quick_config = 0 ';
456 if (!$withInactive) {
457 $query .= ' AND civicrm_price_set.is_active = 1 ';
460 if (self
::eventPriceSetDomainID()) {
461 $query .= ' AND civicrm_price_set.domain_id = ' . CRM_Core_Config
::domainID();
464 $priceSets = array();
466 if ($extendComponentName) {
467 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
471 $query .= " AND civicrm_price_set.extends LIKE '%$componentId%' ";
474 $dao = CRM_Core_DAO
::executeQuery($query);
475 while ($dao->fetch()) {
476 $priceSets[$dao->id
] = $dao->title
;
482 * Get price set details
484 * An array containing price set details (including price fields) is returned
487 * @param bool $required
488 * @param bool $validOnly
490 * @internal param int $setId - price set id whose details are needed
492 * @return array $setTree - array consisting of field details
494 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
498 $priceFields = array(
507 'is_display_amounts',
516 if ($required == TRUE) {
517 $priceFields[] = 'is_required';
521 $select = 'SELECT ' . implode(',', $priceFields);
522 $from = ' FROM civicrm_price_field';
525 $params[1] = array($setID, 'Integer');
527 WHERE price_set_id = %1
532 $currentTime = date('YmdHis');
534 AND ( active_on IS NULL OR active_on <= {$currentTime} )
535 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
539 $orderBy = ' ORDER BY weight';
541 $sql = $select . $from . $where . $dateSelect . $orderBy;
543 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
545 $visibility = CRM_Core_PseudoConstant
::visibility('name');
546 while ($dao->fetch()) {
549 $setTree[$setID]['fields'][$fieldID] = array();
550 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
552 foreach ($priceFields as $field) {
553 if ($field == 'id' ||
is_null($dao->$field)) {
557 if ($field == 'visibility_id') {
558 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
560 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
562 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE);
565 // also get the pre and post help from this price set
567 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
568 FROM civicrm_price_set
570 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
572 $setTree[$setID]['extends'] = $dao->extends;
573 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
574 $setTree[$setID]['help_pre'] = $dao->help_pre
;
575 $setTree[$setID]['help_post'] = $dao->help_post
;
576 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
582 * Get the Price Field ID. We call this function when more than one being present would represent an error
583 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
584 * @param array $priceSet
586 * @throws CRM_Core_Exception
589 public static function getOnlyPriceFieldID(array $priceSet) {
590 if (count($priceSet['fields']) > 1) {
591 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
593 return (int) implode('_', array_keys($priceSet['fields']));
597 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
598 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
599 * @param array $priceSet
601 * @throws CRM_Core_Exception
604 public static function getOnlyPriceFieldValueID(array $priceSet) {
605 $priceFieldID = self
::getOnlyPriceFieldID($priceSet);
606 if (count($priceSet['fields'][$priceFieldID]['options']) > 1) {
607 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
609 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
614 * @param CRM_Core_Form $form
616 * @param string $entityTable
617 * @param bool $validOnly
618 * @param int $priceSetId
620 * @return bool|false|int|null
622 public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
624 $priceSetId = self
::getFor($entityTable, $id);
627 //check if priceset is is_config
628 if (is_numeric($priceSetId)) {
629 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
630 $form->assign('quickConfig', 1);
635 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
636 $entityId = $entity = NULL;
638 switch ($entityTable) {
639 case 'civicrm_event':
640 $entity = 'participant';
641 if (CRM_Utils_System
::getClassName($form) == 'CRM_Event_Form_Participant') {
642 $entityId = $form->_id
;
645 $entityId = $form->_participantId
;
649 case 'civicrm_contribution_page':
650 case 'civicrm_contribution':
651 $entity = 'contribution';
652 $entityId = $form->_id
;
656 if ($entityId && $entity) {
657 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
665 $form->_priceSetId
= $priceSetId;
666 $priceSet = self
::getSetDetail($priceSetId, $required, $validOnly);
667 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
668 $form->_values
['fee'] = CRM_Utils_Array
::value('fields', $form->_priceSet
);
670 //get the price set fields participant count.
671 if ($entityTable == 'civicrm_event') {
672 //get option count info.
673 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
674 if ($form->_priceSet
['optionsCountTotal']) {
675 $optionsCountDeails = array();
676 if (!empty($form->_priceSet
['fields'])) {
677 foreach ($form->_priceSet
['fields'] as $field) {
678 foreach ($field['options'] as $option) {
679 $count = CRM_Utils_Array
::value('count', $option, 0);
680 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
684 $form->_priceSet
['optionsCountDetails'] = $optionsCountDeails;
687 //get option max value info.
688 $optionsMaxValueTotal = 0;
689 $optionsMaxValueDetails = array();
691 if (!empty($form->_priceSet
['fields'])) {
692 foreach ($form->_priceSet
['fields'] as $field) {
693 foreach ($field['options'] as $option) {
694 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
695 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
696 $optionsMaxValueTotal +
= $maxVal;
701 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
702 if ($optionsMaxValueTotal) {
703 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
706 $form->set('priceSetId', $form->_priceSetId
);
707 $form->set('priceSet', $form->_priceSet
);
716 * @param array $params
718 * @param string $component
720 public static function processAmount(&$fields, &$params, &$lineItem, $component = '') {
722 $totalPrice = $totalTax = 0;
723 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
725 $autoRenew = array();
726 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
728 foreach ($fields as $id => $field) {
729 if (empty($params["price_{$id}"]) ||
730 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
732 // skip if nothing was submitted for this field
736 switch ($field['html_type']) {
738 $firstOption = reset($field['options']);
739 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
740 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
741 if (CRM_Utils_Array
::value('tax_rate', $field['options'][key($field['options'])])) {
742 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
743 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
745 if (CRM_Utils_Array
::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
746 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
747 if (array_key_exists($params['financial_type_id'], $taxRates)) {
748 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
749 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
750 $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
751 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
752 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
755 $totalPrice +
= $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[key($field['options'])]);
759 //special case if user select -none-
760 if ($params["price_{$id}"] <= 0) {
763 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
764 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
765 $optionLabel = CRM_Utils_Array
::value('label', $field['options'][$optionValueId]);
766 $params['amount_priceset_level_radio'] = array();
767 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
768 if (isset($radioLevel)) {
769 $radioLevel = array_merge($radioLevel,
770 array_keys($params['amount_priceset_level_radio'])
774 $radioLevel = array_keys($params['amount_priceset_level_radio']);
776 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
777 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
778 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
779 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
780 if (CRM_Utils_Array
::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
781 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule
::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
784 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
787 // auto_renew exists and is empty in some workflows, which php treat as a 0
788 // and hence we explicitly check to see if auto_renew is numeric
789 isset($lineItem[$optionValueId]['auto_renew']) &&
790 is_numeric($lineItem[$optionValueId]['auto_renew'])
792 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
797 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
798 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
799 $optionLabel = $field['options'][$optionValueId]['label'];
800 $params['amount_priceset_level_select'] = array();
801 $params['amount_priceset_level_select'][CRM_Utils_Array
::key(1, $params["price_{$id}"])] = $optionLabel;
802 if (isset($selectLevel)) {
803 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
806 $selectLevel = array_keys($params['amount_priceset_level_select']);
808 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
809 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
810 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
811 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
813 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
816 isset($lineItem[$optionValueId]['auto_renew']) &&
817 is_numeric($lineItem[$optionValueId]['auto_renew'])
819 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
824 $params['amount_priceset_level_checkbox'] = $optionIds = array();
825 foreach ($params["price_{$id}"] as $optionId => $option) {
826 $optionIds[] = $optionId;
827 $optionLabel = $field['options'][$optionId]['label'];
828 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
829 if (isset($checkboxLevel)) {
830 $checkboxLevel = array_unique(array_merge(
832 array_keys($params['amount_priceset_level_checkbox'])
837 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
840 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
841 foreach ($optionIds as $optionId) {
842 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionId])) {
843 $lineItem = self
::setLineItem($field, $lineItem, $optionId);
844 $totalTax +
= $field['options'][$optionId]['tax_amount'];
846 $totalPrice +
= $lineItem[$optionId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionId]);
849 isset($lineItem[$optionId]['auto_renew']) &&
850 is_numeric($lineItem[$optionId]['auto_renew'])
852 $autoRenew[$lineItem[$optionId]['auto_renew']] +
= $lineItem[$optionId]['line_total'];
859 $amount_level = array();
860 $totalParticipant = 0;
861 if (is_array($lineItem)) {
862 foreach ($lineItem as $values) {
863 $totalParticipant +
= $values['participant_count'];
864 if ($values['html_type'] == 'Text') {
865 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
868 $amount_level[] = $values['label'];
872 $displayParticipantCount = '';
873 if ($totalParticipant > 0) {
874 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
876 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
877 $params['amount'] = $totalPrice;
878 $params['tax_amount'] = $totalTax;
880 foreach ($autoRenew as $dontCare => $eachAmount) {
882 unset($autoRenew[$dontCare]);
885 if (count($autoRenew) > 1) {
886 $params['autoRenew'] = $autoRenew;
892 * Build the price set form.
894 * @param CRM_Core_Form $form
898 public static function buildPriceSet(&$form) {
899 $priceSetId = $form->get('priceSetId');
904 $validFieldsOnly = TRUE;
905 $className = CRM_Utils_System
::getClassName($form);
906 if (in_array($className, array(
907 'CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'))) {
908 $validFieldsOnly = FALSE;
911 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
912 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
913 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
914 $form->_quickConfig
= $quickConfig = 0;
915 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
919 $form->assign('quickConfig', $quickConfig);
920 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
921 $form->_quickConfig
= $quickConfig;
923 $form->assign('priceSet', $form->_priceSet
);
925 $component = 'contribution';
926 if ($className == 'CRM_Member_Form_Membership') {
927 $component = 'membership';
930 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
931 $feeBlock = &$form->_values
['fee'];
932 if (!empty($form->_useForMember
)) {
933 $component = 'membership';
937 $feeBlock = &$form->_priceSet
['fields'];
941 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
943 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
944 $adminFieldVisible = FALSE;
945 if (CRM_Core_Permission
::check('administer CiviCRM')) {
946 $adminFieldVisible = TRUE;
949 foreach ($feeBlock as $id => $field) {
950 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
951 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
954 $options = CRM_Utils_Array
::value('options', $field);
955 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
956 $userid = $form->getVar('_membershipContactID');
957 $checklifetime = self
::checkCurrentMembership($options, $userid);
958 if ($checklifetime) {
959 $form->assign('ispricelifetime', TRUE);
962 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
965 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
966 'price_' . $field['id'],
969 CRM_Utils_Array
::value('is_required', $field, FALSE),
978 * Check the current Membership
979 * having end date null.
981 public static function checkCurrentMembership(&$options, $userid) {
982 if (!$userid ||
empty($options)) {
985 static $_contact_memberships = array();
986 $checklifetime = FALSE;
987 foreach ($options as $key => $value) {
988 if (!empty($value['membership_type_id'])) {
989 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
990 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
992 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
993 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
994 unset($options[$key]);
995 $checklifetime = TRUE;
999 if ($checklifetime) {
1008 * Set daefult the price set fields.
1010 * @param CRM_Core_Form $form
1013 * @return array $defaults
1015 public static function setDefaultPriceSet(&$form, &$defaults) {
1016 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
1020 foreach ($form->_priceSet
['fields'] as $key => $val) {
1021 foreach ($val['options'] as $keys => $values) {
1022 if ($values['is_default']) {
1023 if ($val['html_type'] == 'CheckBox') {
1024 $defaults["price_{$key}"][$keys] = 1;
1027 $defaults["price_{$key}"] = $keys;
1036 * Supports event create function by setting up required price sets, not tested but expect
1037 * it will work for contribution page
1038 * @param array $params
1039 * As passed to api/bao create fn.
1040 * @param CRM_Core_DAO $entity
1041 * Object for given entity.
1042 * @param string $entityName
1043 * Name of entity - e.g event.
1045 public static function setPriceSets(&$params, $entity, $entityName) {
1046 if (empty($params['price_set_id']) ||
!is_array($params['price_set_id'])) {
1049 // CRM-14069 note that we may as well start by assuming more than one.
1050 // currently the form does not pass in as an array & will be skipped
1051 // test is passing in as an array but I feel the api should have a metadata that allows
1052 // transform of single to array - seems good for managing transitions - in which case all api
1053 // calls that set price_set_id will hit this
1054 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1055 // all separated values, strings, json half-separated values (in participant we hit this)
1056 // to be converted to json @ api layer
1057 $pse = new CRM_Price_DAO_PriceSetEntity();
1058 $pse->entity_table
= 'civicrm_' . $entityName;
1059 $pse->entity_id
= $entity->id
;
1060 while ($pse->fetch()) {
1061 if (!in_array($pse->price_set_id
, $params['price_set_id'])) {
1062 // note an even more aggressive form of this deletion currently happens in event form
1063 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1064 // on the participant record
1065 if (CRM_Price_BAO_PriceSet
::removeFrom('civicrm_' . $entityName, $entity->id
)) {
1066 CRM_Core_BAO_Discount
::del($entity->id
, 'civicrm_' . $entityName);
1070 foreach ($params['price_set_id'] as $priceSetID) {
1071 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $entityName, $entity->id
, $priceSetID);
1072 //@todo - how should we do this - copied from form
1073 //if (CRM_Utils_Array::value('price_field_id', $params)) {
1074 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1075 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1080 * Get field ids of a price set
1085 * @return array of the field ids
1089 public static function getFieldIds($id) {
1090 $priceField = new CRM_Price_DAO_PriceField();
1091 $priceField->price_set_id
= $id;
1092 $priceField->find();
1093 while ($priceField->fetch()) {
1094 $var[] = $priceField->id
;
1100 * This function is to make a copy of a price set, including
1104 * The price set id to copy.
1106 * @return the copy object
1109 public static function copy($id) {
1110 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1112 $title = ts('[Copy id %1]', array(1 => $maxId +
1));
1115 'title' => ' ' . $title,
1116 'name' => '__Copy_id_' . ($maxId +
1) . '_',
1120 $copy = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1126 //copying all the blocks pertaining to the price set
1127 $copyPriceField = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1128 array('price_set_id' => $id),
1129 array('price_set_id' => $copy->id
)
1131 if (!empty($copyPriceField)) {
1132 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1134 //copy option group and values
1135 foreach ($price as $originalId => $copyId) {
1136 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1137 array('price_field_id' => $originalId),
1138 array('price_field_id' => $copyId)
1144 CRM_Utils_Hook
::copy('Set', $copy);
1149 * This function is to check price set permission
1156 public static function checkPermission($sid) {
1157 if ($sid && self
::eventPriceSetDomainID()) {
1158 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1159 if (CRM_Core_Config
::domainID() != $domain_id) {
1160 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
1167 * Get the sum of participant count
1168 * for all fields of given price set.
1173 * @param bool $onlyActive
1175 * @return int|null|string
1178 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1186 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1189 static $pricesetFieldCount = array();
1190 if (!isset($pricesetFieldCount[$sid])) {
1192 SELECT sum(value.count) as totalCount
1193 FROM civicrm_price_field_value value
1194 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1195 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1199 $count = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1200 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1203 return $pricesetFieldCount[$sid];
1211 public static function getMembershipCount($ids) {
1213 SELECT count( pfv.id ) AS count, pfv.id AS id
1214 FROM civicrm_price_field_value pfv
1215 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1216 WHERE pfv.id IN ( $ids )
1217 GROUP BY mt.member_of_contact_id";
1219 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1222 while ($crmDAO->fetch()) {
1223 $count[$crmDAO->id
] = $crmDAO->count
;
1230 * Check if auto renew option should be shown
1232 * @param int $priceSetId
1235 * @return int $autoRenewOption ( 0:hide, 1:optional 2:required )
1237 public static function checkAutoRenewForPriceSet($priceSetId) {
1238 // auto-renew option should be visible if membership types associated with all the fields has
1239 // been set for auto-renew option
1240 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1242 // get the membership type auto renew option and check if required or optional
1243 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1244 FROM civicrm_price_field_value pfv
1245 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1246 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1247 WHERE pf.price_set_id = %1
1248 AND pf.is_active = 1
1249 AND pfv.is_active = 1';
1251 $params = array(1 => array($priceSetId, 'Integer'));
1253 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1254 $autoRenewOption = 2;
1255 $interval = $unit = array();
1256 while ($dao->fetch()) {
1257 if (!$dao->auto_renew
) {
1258 $autoRenewOption = 0;
1261 if ($dao->auto_renew
== 1) {
1262 $autoRenewOption = 1;
1265 $interval[$dao->duration_interval
] = $dao->duration_interval
;
1266 $unit[$dao->duration_unit
] = $dao->duration_unit
;
1269 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1270 return $autoRenewOption;
1278 * Retrieve auto renew frequency and interval
1280 * @param int $priceSetId
1283 * @return array associate array of frequency interval and unit
1286 public static function getRecurDetails($priceSetId) {
1287 $query = 'SELECT mt.duration_interval, mt.duration_unit
1288 FROM civicrm_price_field_value pfv
1289 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1290 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1291 WHERE pf.price_set_id = %1 LIMIT 1';
1293 $params = array(1 => array($priceSetId, 'Integer'));
1294 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1296 return array($dao->duration_interval
, $dao->duration_unit
);
1302 public static function eventPriceSetDomainID() {
1303 return CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
1304 'event_price_set_domain_id',
1310 * Update the is_quick_config flag in the db
1313 * Id of the database record.
1314 * @param bool $isQuickConfigValue we want to set the is_quick_config field.
1315 * Value we want to set the is_quick_config field.
1317 * @return Object DAO object on sucess, null otherwise
1320 public static function setIsQuickConfig($id, $isQuickConfig) {
1321 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1325 * Check if price set id provides option for
1326 * user to select both auto-renew and non-auto-renew memberships
1331 public static function checkMembershipPriceSet($id) {
1334 SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1335 FROM civicrm_price_field_value pfv
1336 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1337 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1338 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1342 $params = array(1 => array($id, 'Integer'));
1343 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1345 $autoRenew = array();
1346 //FIXME: do a comprehensive check of whether
1347 //2 membership types can be selected
1348 //instead of comparing all of them
1349 while ($dao->fetch()) {
1350 //temp fix for #CRM-10370
1351 //if its NULL consider it '0' i.e. 'No auto-renew option'
1352 $daoAutoRenew = $dao->auto_renew
;
1353 if ($daoAutoRenew === NULL) {
1356 if (!empty($autoRenew) && !in_array($daoAutoRenew, $autoRenew)) {
1359 $autoRenew[] = $daoAutoRenew;
1365 * Copy priceSet when event/contibution page is copied
1367 * @param string $baoName
1370 * Old event/contribution page id.
1372 * Newly created event/contribution page id.
1374 public static function copyPriceSet($baoName, $id, $newId) {
1375 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1377 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1378 if ($isQuickConfig) {
1379 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($priceSetId);
1380 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1383 $copyPriceSet = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1386 'entity_table' => $baoName,
1388 array('entity_id' => $newId)
1391 // copy event discount
1392 if ($baoName == 'civicrm_event') {
1393 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1394 foreach ($discount as $discountId => $setId) {
1396 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1398 CRM_Core_DAO
::copyGeneric(
1399 'CRM_Core_DAO_Discount',
1401 'id' => $discountId,
1404 'entity_id' => $newId,
1405 'price_set_id' => $copyPriceSet->id
,
1414 * Function to set tax_amount and tax_rate in LineItem
1418 public static function setLineItem($field, $lineItem, $optionValueId) {
1419 if ($field['html_type'] == 'Text') {
1420 $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
1423 $taxAmount = $field['options'][$optionValueId]['tax_amount'];
1425 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1426 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1427 $lineItem[$optionValueId]['tax_rate'] = $taxRate;