3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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
{
45 function __construct() {
46 parent
::__construct();
50 * takes an associative array and creates a price set object
52 * @param array $params (reference) an assoc array of name/value pairs
54 * @return object CRM_Price_DAO_PriceSet object
58 static function create(&$params) {
59 if(empty($params['id']) && empty($params['name'])) {
60 $params['name'] = CRM_Utils_String
::munge($params['title'], '_', 242);
62 $priceSetBAO = new CRM_Price_BAO_PriceSet();
63 $priceSetBAO->copyValues($params);
64 if (self
::eventPriceSetDomainID()) {
65 $priceSetBAO->domain_id
= CRM_Core_Config
::domainID();
67 return $priceSetBAO->save();
71 * Takes a bunch of params that are needed to match certain criteria and
72 * retrieves the relevant objects. Typically the valid params are only
73 * contact_id. We'll tweak this function to be more full featured over a period
74 * of time. This is the inverse function of create. It also stores all the retrieved
75 * values in the default array
77 * @param array $params (reference ) an assoc array of name/value pairs
78 * @param array $defaults (reference ) an assoc array to hold the flattened values
80 * @return object CRM_Price_DAO_PriceSet object
84 static function retrieve(&$params, &$defaults) {
85 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
89 * update the is_active flag in the db
91 * @param int $id id of the database record
94 * @internal param bool $is_active value we want to set the is_active field
96 * @return Object DAO object on sucess, null otherwise
100 static function setIsActive($id, $isActive) {
101 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
105 * Calculate the default price set id
106 * assigned to the contribution/membership etc
108 * @param string $entity
110 * @return array $defaultPriceSet default price set
116 public static function getDefaultPriceSet($entity = 'contribution') {
118 $entityName = 'default_contribution_amount';
119 if ($entity == 'membership') {
120 $entityName = 'default_membership_type_amount';
124 SELECT ps.id AS setID, pfv.price_field_id AS priceFieldID, pfv.id AS priceFieldValueID, pfv.name, pfv.label
125 FROM civicrm_price_set ps
126 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
127 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
128 WHERE ps.name = '{$entityName}'
131 $dao = CRM_Core_DAO
::executeQuery($sql);
132 $defaultPriceSet = array();
133 while ($dao->fetch()) {
134 $defaultPriceSet[$dao->priceFieldValueID
]['setID'] = $dao->setID
;
135 $defaultPriceSet[$dao->priceFieldValueID
]['priceFieldID'] = $dao->priceFieldID
;
136 $defaultPriceSet[$dao->priceFieldValueID
]['name'] = $dao->name
;
137 $defaultPriceSet[$dao->priceFieldValueID
]['label'] = $dao->label
;
138 $defaultPriceSet[$dao->priceFieldValueID
]['priceFieldValueID'] = $dao->priceFieldValueID
;
141 return $defaultPriceSet;
145 * Get the price set title.
147 * @param int $id id of price set
149 * @return string title
155 public static function getTitle($id) {
156 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
160 * Return a list of all forms which use this price set.
162 * @param int $id id of price set
163 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
167 public static function &getUsedBy($id, $simpleReturn = FALSE) {
168 $usedBy = $forms = $tables = array();
170 SELECT entity_table, entity_id
171 FROM civicrm_price_set_entity
172 WHERE price_set_id = %1";
173 $params = array(1 => array($id, 'Integer'));
174 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
176 while ($crmFormDAO->fetch()) {
177 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
178 $tables[] = $crmFormDAO->entity_table
;
180 // Return only tables
181 if ($simpleReturn == 'table') {
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 = array(1 => array($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
;
200 // Return only entity data
201 if ($simpleReturn == 'entity') {
204 foreach ($forms as $table => $entities) {
206 case 'civicrm_event':
207 $ids = implode(',', $entities);
208 $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
209 FROM civicrm_event ce
210 LEFT JOIN civicrm_option_value ON
211 ( ce.event_type_id = civicrm_option_value.value )
212 LEFT JOIN civicrm_option_group ON
213 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
215 civicrm_option_group.name = 'event_type' AND
218 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
219 while ($crmDAO->fetch()) {
220 if ($crmDAO->isTemplate
) {
221 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
222 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
223 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
226 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
227 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
228 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
229 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
230 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
235 case 'civicrm_contribution_page':
236 $ids = implode(',', $entities);
237 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
238 FROM civicrm_contribution_page cp, civicrm_financial_type ct
239 WHERE ct.id = cp.financial_type_id AND
242 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
243 while ($crmDAO->fetch()) {
244 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
245 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
246 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
247 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
251 case 'civicrm_contribution':
252 case 'civicrm_membership':
253 case 'civicrm_participant':
258 CRM_Core_Error
::fatal("$table is not supported in PriceSet::usedBy()");
267 * Delete the price set
269 * @param int $id Price Set id
271 * @return boolean false if fields exist for this set, true if the
272 * set could be deleted
277 public static function deleteSet($id) {
278 // remove from all inactive forms
279 $usedBy = self
::getUsedBy($id);
280 if (isset($usedBy['civicrm_event'])) {
281 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
282 $eventDAO = new CRM_Event_DAO_Event();
283 $eventDAO->id
= $eventId;
285 while ($eventDAO->fetch()) {
286 self
::removeFrom('civicrm_event', $eventDAO->id
);
291 // delete price fields
292 $priceField = new CRM_Price_DAO_PriceField();
293 $priceField->price_set_id
= $id;
295 while ($priceField->fetch()) {
296 // delete options first
297 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
300 $set = new CRM_Price_DAO_PriceSet();
302 return $set->delete();
306 * Link the price set with the specified table and id
308 * @param string $entityTable
309 * @param integer $entityId
310 * @param integer $priceSetId
314 public static function addTo($entityTable, $entityId, $priceSetId) {
315 // verify that the price set exists
316 $dao = new CRM_Price_DAO_PriceSet();
317 $dao->id
= $priceSetId;
323 $dao = new CRM_Price_DAO_PriceSetEntity();
324 // find if this already exists
325 $dao->entity_id
= $entityId;
326 $dao->entity_table
= $entityTable;
329 // add or update price_set_id
330 $dao->price_set_id
= $priceSetId;
335 * Delete price set for the given entity and id
337 * @param string $entityTable
338 * @param integer $entityId
342 public static function removeFrom($entityTable, $entityId) {
343 $dao = new CRM_Price_DAO_PriceSetEntity();
344 $dao->entity_table
= $entityTable;
345 $dao->entity_id
= $entityId;
346 return $dao->delete();
350 * Find a price_set_id associatied with the given table, id and usedFor
351 * Used For value for events:1, contribution:2, membership:3
353 * @param string $entityTable
354 * @param int $entityId
355 * @param int $usedFor ( price set that extends/used for particular component )
357 * @param null $isQuickConfig
358 * @param null $setName
360 * @return integer|false price_set_id, or false if none found
362 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
363 if (!$entityTable ||
!$entityId) {
367 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
368 FROM civicrm_price_set ps
369 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
370 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
371 if ($isQuickConfig) {
372 $sql .= ' AND ps.is_quick_config = 0 ';
374 $params = array(1 => array($entityTable, 'String'),
375 2 => array($entityId, 'Integer'),
378 $sql .= " AND ps.extends LIKE '%%3%' ";
379 $params[3] = array($usedFor, 'Integer');
382 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
384 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
385 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
389 * Find a price_set_id associated with the given option value or field ID
391 * @param array $params (reference) an assoc array of name/value pairs
392 * array may contain either option id or
395 * @return integer|NULL price set id on success, null otherwise
399 public static function getSetId(&$params) {
402 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
403 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
404 $fieldValue->id
= $oid;
405 if ($fieldValue->find(TRUE)) {
406 $fid = $fieldValue->price_field_id
;
410 $fid = CRM_Utils_Array
::value('fid', $params);
414 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
421 * Return an associative array of all price sets
423 * @param bool $withInactive whether or not to include inactive entries
424 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
426 * @return array associative array of id => name
428 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE) {
431 DISTINCT ( price_set_id ) as id, title
436 civicrm_price_set.id = civicrm_price_field.price_set_id AND is_quick_config = 0 ';
438 if (!$withInactive) {
439 $query .= ' AND civicrm_price_set.is_active = 1 ';
442 if (self
::eventPriceSetDomainID()) {
443 $query .= ' AND civicrm_price_set.domain_id = ' . CRM_Core_Config
::domainID();
446 $priceSets = array();
448 if ($extendComponentName) {
449 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
453 $query .= " AND civicrm_price_set.extends LIKE '%$componentId%' ";
456 $dao = CRM_Core_DAO
::executeQuery($query);
457 while ($dao->fetch()) {
458 $priceSets[$dao->id
] = $dao->title
;
464 * Get price set details
466 * An array containing price set details (including price fields) is returned
469 * @param bool $required
470 * @param bool $validOnly
472 * @internal param int $setId - price set id whose details are needed
474 * @return array $setTree - array consisting of field details
476 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
480 $priceFields = array(
489 'is_display_amounts',
498 if ($required == TRUE) {
499 $priceFields[] = 'is_required';
503 $select = 'SELECT ' . implode(',', $priceFields);
504 $from = ' FROM civicrm_price_field';
507 $params[1] = array($setID, 'Integer');
509 WHERE price_set_id = %1
514 $currentTime = date('YmdHis');
516 AND ( active_on IS NULL OR active_on <= {$currentTime} )
517 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
521 $orderBy = ' ORDER BY weight';
523 $sql = $select . $from . $where . $dateSelect . $orderBy;
525 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
527 $visibility = CRM_Core_PseudoConstant
::visibility('name');
528 while ($dao->fetch()) {
531 $setTree[$setID]['fields'][$fieldID] = array();
532 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
534 foreach ($priceFields as $field) {
535 if ($field == 'id' ||
is_null($dao->$field)) {
539 if ($field == 'visibility_id') {
540 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
542 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
544 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE);
547 // also get the pre and post help from this price set
549 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
550 FROM civicrm_price_set
552 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
554 $setTree[$setID]['extends'] = $dao->extends;
555 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
556 $setTree[$setID]['help_pre'] = $dao->help_pre
;
557 $setTree[$setID]['help_post'] = $dao->help_post
;
558 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
564 * @param CRM_Core_Form $form
566 * @param string $entityTable
567 * @param bool $validOnly
568 * @param null $priceSetId
570 * @return bool|false|int|null
572 static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
574 $priceSetId = self
::getFor($entityTable, $id);
577 //check if priceset is is_config
578 if (is_numeric($priceSetId)) {
579 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
580 $form->assign('quickConfig', 1);
585 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
586 $entityId = $entity = NULL;
588 switch ($entityTable) {
589 case 'civicrm_event':
590 $entity = 'participant';
591 if (CRM_Utils_System
::getClassName($form) == 'CRM_Event_Form_Participant') {
592 $entityId = $form->_id
;
595 $entityId = $form->_participantId
;
599 case 'civicrm_contribution_page':
600 case 'civicrm_contribution':
601 $entity = 'contribution';
602 $entityId = $form->_id
;
606 if ($entityId && $entity) {
607 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
615 $form->_priceSetId
= $priceSetId;
616 $priceSet = self
::getSetDetail($priceSetId, $required, $validOnly);
617 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
618 $form->_values
['fee'] = CRM_Utils_Array
::value('fields', $form->_priceSet
);
620 //get the price set fields participant count.
621 if ($entityTable == 'civicrm_event') {
622 //get option count info.
623 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
624 if ($form->_priceSet
['optionsCountTotal']) {
625 $optionsCountDeails = array();
626 if (!empty($form->_priceSet
['fields'])) {
627 foreach ($form->_priceSet
['fields'] as $field) {
628 foreach ($field['options'] as $option) {
629 $count = CRM_Utils_Array
::value('count', $option, 0);
630 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
634 $form->_priceSet
['optionsCountDetails'] = $optionsCountDeails;
637 //get option max value info.
638 $optionsMaxValueTotal = 0;
639 $optionsMaxValueDetails = array();
641 if (!empty($form->_priceSet
['fields'])) {
642 foreach ($form->_priceSet
['fields'] as $field) {
643 foreach ($field['options'] as $option) {
644 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
645 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
646 $optionsMaxValueTotal +
= $maxVal;
651 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
652 if ($optionsMaxValueTotal) {
653 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
656 $form->set('priceSetId', $form->_priceSetId
);
657 $form->set('priceSet', $form->_priceSet
);
668 * @param string $component
670 static function processAmount(&$fields, &$params, &$lineItem, $component = '') {
673 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
675 $autoRenew = array();
676 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
678 foreach ($fields as $id => $field) {
679 if (empty($params["price_{$id}"]) ||
680 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
682 // skip if nothing was submitted for this field
686 switch ($field['html_type']) {
688 $params["price_{$id}"] = array(key($field['options']) => $params["price_{$id}"]);
689 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
690 $totalPrice +
= $lineItem[key($field['options'])]['line_total'];
694 //special case if user select -none-
695 if ($params["price_{$id}"] <= 0) {
698 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
699 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
700 $optionLabel = CRM_Utils_Array
::value('label', $field['options'][$optionValueId]);
701 $params['amount_priceset_level_radio'] = array();
702 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
703 if (isset($radioLevel)) {
704 $radioLevel = array_merge($radioLevel,
705 array_keys($params['amount_priceset_level_radio'])
709 $radioLevel = array_keys($params['amount_priceset_level_radio']);
711 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
712 $totalPrice +
= $lineItem[$optionValueId]['line_total'];
715 // auto_renew exists and is empty in some workflows, which php treat as a 0
716 // and hence we explicitly check to see if auto_renew is numeric
717 isset($lineItem[$optionValueId]['auto_renew']) &&
718 is_numeric($lineItem[$optionValueId]['auto_renew'])
720 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
725 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
726 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
727 $optionLabel = $field['options'][$optionValueId]['label'];
728 $params['amount_priceset_level_select'] = array();
729 $params['amount_priceset_level_select'][CRM_Utils_Array
::key(1, $params["price_{$id}"])] = $optionLabel;
730 if (isset($selectLevel)) {
731 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
734 $selectLevel = array_keys($params['amount_priceset_level_select']);
736 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
737 $totalPrice +
= $lineItem[$optionValueId]['line_total'];
740 isset($lineItem[$optionValueId]['auto_renew']) &&
741 is_numeric($lineItem[$optionValueId]['auto_renew'])
743 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
748 $params['amount_priceset_level_checkbox'] = $optionIds = array();
749 foreach ($params["price_{$id}"] as $optionId => $option) {
750 $optionIds[] = $optionId;
751 $optionLabel = $field['options'][$optionId]['label'];
752 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
753 if (isset($checkboxLevel)) {
754 $checkboxLevel = array_unique(array_merge(
756 array_keys($params['amount_priceset_level_checkbox'])
761 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
764 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
765 foreach ($optionIds as $optionId) {
766 $totalPrice +
= $lineItem[$optionId]['line_total'];
769 isset($lineItem[$optionId]['auto_renew']) &&
770 is_numeric($lineItem[$optionId]['auto_renew'])
772 $autoRenew[$lineItem[$optionId]['auto_renew']] +
= $lineItem[$optionId]['line_total'];
779 $amount_level = array();
780 $totalParticipant = 0;
781 if (is_array($lineItem)) {
782 foreach ($lineItem as $values) {
783 $totalParticipant +
= $values['participant_count'];
784 if ($values['html_type'] == 'Text') {
785 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
788 $amount_level[] = $values['label'];
792 $displayParticipantCount = '';
793 if ($totalParticipant > 0) {
794 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
796 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
797 $params['amount'] = $totalPrice;
799 foreach ($autoRenew as $dontCare => $eachAmount) {
801 unset($autoRenew[$dontCare]);
804 if (count($autoRenew) > 1 ) {
805 $params['autoRenew'] = $autoRenew;
811 * Function to build the price set form.
813 * @param CRM_Core_Form $form
818 static function buildPriceSet(&$form) {
819 $priceSetId = $form->get('priceSetId');
820 $userid = $form->getVar('_userID');
825 $validFieldsOnly = TRUE;
826 $className = CRM_Utils_System
::getClassName($form);
827 if (in_array($className, array(
828 'CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'))) {
829 $validFieldsOnly = FALSE;
832 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
833 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
834 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
835 $form->_quickConfig
= $quickConfig = 0;
836 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
840 $form->assign('quickConfig', $quickConfig);
841 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
842 $form->_quickConfig
= $quickConfig;
844 $form->assign('priceSet', $form->_priceSet
);
846 $component = 'contribution';
847 if ($className == 'CRM_Member_Form_Membership') {
848 $component = 'membership';
851 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
852 $feeBlock = &$form->_values
['fee'];
853 if (!empty($form->_useForMember
)) {
854 $component = 'membership';
858 $feeBlock = &$form->_priceSet
['fields'];
862 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
864 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
865 $adminFieldVisible = false;
866 if (CRM_Core_Permission
::check('administer CiviCRM')) {
867 $adminFieldVisible = true;
870 foreach ($feeBlock as $id => $field) {
871 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
872 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == true) ||
875 $options = CRM_Utils_Array
::value('options', $field);
876 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
877 $checklifetime = self
::checkCurrentMembership($options, $userid);
878 if ($checklifetime) {
879 $form->assign('ispricelifetime', TRUE);
882 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
885 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
886 'price_' . $field['id'],
889 CRM_Utils_Array
::value('is_required', $field, FALSE),
898 * Function to check the current Membership
899 * having end date null.
901 static function checkCurrentMembership(&$options, $userid) {
902 if (!$userid ||
empty($options)) {
905 static $_contact_memberships = array();
906 $checklifetime = FALSE;
907 foreach ($options as $key => $value) {
908 if (!empty($value['membership_type_id'])) {
909 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
910 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
912 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
913 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
914 unset($options[$key]);
915 $checklifetime = TRUE;
919 if ($checklifetime) {
928 * Function to set daefult the price set fields.
933 * @return array $defaults
936 static function setDefaultPriceSet(&$form, &$defaults) {
937 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
941 foreach ($form->_priceSet
['fields'] as $key => $val) {
942 foreach ($val['options'] as $keys => $values) {
943 if ($values['is_default']) {
944 if ($val['html_type'] == 'CheckBox') {
945 $defaults["price_{$key}"][$keys] = 1;
948 $defaults["price_{$key}"] = $keys;
957 * Get field ids of a price set
959 * @param int $id Price Set id
961 * @return array of the field ids
966 public static function getFieldIds($id) {
967 $priceField = new CRM_Price_DAO_PriceField();
968 $priceField->price_set_id
= $id;
970 while ($priceField->fetch()) {
971 $var[] = $priceField->id
;
977 * This function is to make a copy of a price set, including
980 * @param int $id the price set id to copy
982 * @return the copy object
986 static function copy($id) {
987 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
989 $title = ts('[Copy id %1]', array(1 => $maxId +
1));
991 'suffix' => array('title' => ' ' . $title,
992 'name' => '__Copy_id_' . ($maxId +
1) . '_',
996 $copy = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1002 //copying all the blocks pertaining to the price set
1003 $copyPriceField = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1004 array('price_set_id' => $id),
1005 array('price_set_id' => $copy->id
)
1007 if (!empty($copyPriceField)) {
1008 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1010 //copy option group and values
1011 foreach ($price as $originalId => $copyId) {
1012 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1013 array('price_field_id' => $originalId),
1014 array('price_field_id' => $copyId)
1020 CRM_Utils_Hook
::copy('Set', $copy);
1025 * This function is to check price set permission
1027 * @param int $sid the price set id
1031 static function checkPermission($sid) {
1032 if ($sid && self
::eventPriceSetDomainID()) {
1033 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1034 if (CRM_Core_Config
::domainID() != $domain_id) {
1035 CRM_Core_Error
::fatal(ts('You do not have permission to access this page'));
1042 * Get the sum of participant count
1043 * for all fields of given price set.
1045 * @param int $sid the price set id
1047 * @param bool $onlyActive
1049 * @return int|null|string
1053 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1061 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1064 static $pricesetFieldCount = array();
1065 if (!isset($pricesetFieldCount[$sid])) {
1067 SELECT sum(value.count) as totalCount
1068 FROM civicrm_price_field_value value
1069 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1070 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1074 $count = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1075 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1078 return $pricesetFieldCount[$sid];
1086 public static function getMembershipCount($ids) {
1088 SELECT count( pfv.id ) AS count, pfv.id AS id
1089 FROM civicrm_price_field_value pfv
1090 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1091 WHERE pfv.id IN ( $ids )
1092 GROUP BY mt.member_of_contact_id";
1094 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1097 while ($crmDAO->fetch()) {
1098 $count[$crmDAO->id
] = $crmDAO->count
;
1105 * Function to check if auto renew option should be shown
1107 * @param int $priceSetId price set id
1109 * @return int $autoRenewOption ( 0:hide, 1:optional 2:required )
1111 public static function checkAutoRenewForPriceSet($priceSetId) {
1112 // auto-renew option should be visible if membership types associated with all the fields has
1113 // been set for auto-renew option
1114 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1116 // get the membership type auto renew option and check if required or optional
1117 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1118 FROM civicrm_price_field_value pfv
1119 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1120 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1121 WHERE pf.price_set_id = %1
1122 AND pf.is_active = 1
1123 AND pfv.is_active = 1';
1125 $params = array(1 => array($priceSetId, 'Integer'));
1127 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1128 $autoRenewOption = 2;
1129 $interval = $unit = array();
1130 while ($dao->fetch()) {
1131 if (!$dao->auto_renew
) {
1132 $autoRenewOption = 0;
1135 if ($dao->auto_renew
== 1) {
1136 $autoRenewOption = 1;
1139 $interval[$dao->duration_interval
] = $dao->duration_interval
;
1140 $unit[$dao->duration_unit
] = $dao->duration_unit
;
1143 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1144 return $autoRenewOption;
1152 * Function to retrieve auto renew frequency and interval
1154 * @param int $priceSetId price set id
1156 * @return array associate array of frequency interval and unit
1160 public static function getRecurDetails($priceSetId) {
1161 $query = 'SELECT mt.duration_interval, mt.duration_unit
1162 FROM civicrm_price_field_value pfv
1163 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1164 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1165 WHERE pf.price_set_id = %1 LIMIT 1';
1167 $params = array(1 => array($priceSetId, 'Integer'));
1168 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1170 return array($dao->duration_interval
, $dao->duration_unit
);
1176 static function eventPriceSetDomainID() {
1177 return CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
1178 'event_price_set_domain_id',
1184 * update the is_quick_config flag in the db
1186 * @param int $id id of the database record
1187 * @param boolean $isQuickConfig value we want to set the is_quick_config field
1189 * @return Object DAO object on sucess, null otherwise
1193 static function setIsQuickConfig($id, $isQuickConfig) {
1194 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1198 * Check if price set id provides option for
1199 * user to select both auto-renew and non-auto-renew memberships
1205 public static function checkMembershipPriceSet($id) {
1208 SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1209 FROM civicrm_price_field_value pfv
1210 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1211 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1212 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1216 $params = array(1 => array($id, 'Integer'));
1217 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1219 $autoRenew = array();
1220 //FIXME: do a comprehensive check of whether
1221 //2 membership types can be selected
1222 //instead of comparing all of them
1223 while ($dao->fetch()) {
1224 //temp fix for #CRM-10370
1225 //if its NULL consider it '0' i.e. 'No auto-renew option'
1226 $daoAutoRenew = $dao->auto_renew
;
1227 if ($daoAutoRenew === NULL) {
1230 if (!empty($autoRenew) && !in_array($daoAutoRenew, $autoRenew)) {
1233 $autoRenew[] = $daoAutoRenew;
1239 * Copy priceSet when event/contibution page is copied
1241 * @params string $baoName BAO name
1242 * @params int $id old event/contribution page id
1243 * @params int $newId newly created event/contribution page id
1245 * @param string $baoName
1246 * @param integer $id
1247 * @param integer $newId
1249 static function copyPriceSet($baoName, $id, $newId) {
1250 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1252 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1253 if($isQuickConfig) {
1254 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($priceSetId);
1255 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1258 $copyPriceSet = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1261 'entity_table' => $baoName,
1263 array('entity_id' => $newId)
1266 // copy event discount
1267 if ($baoName == 'civicrm_event') {
1268 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1269 foreach ($discount as $discountId => $setId) {
1271 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1273 CRM_Core_DAO
::copyGeneric(
1274 'CRM_Core_DAO_Discount',
1276 'id' => $discountId,
1279 'entity_id' => $newId,
1280 'price_set_id' => $copyPriceSet->id
,