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 $priceSetBAO = new CRM_Price_BAO_PriceSet();
60 $priceSetBAO->copyValues($params);
61 if (self
::eventPriceSetDomainID()) {
62 $priceSetBAO->domain_id
= CRM_Core_Config
::domainID();
64 return $priceSetBAO->save();
68 * Takes a bunch of params that are needed to match certain criteria and
69 * retrieves the relevant objects. Typically the valid params are only
70 * contact_id. We'll tweak this function to be more full featured over a period
71 * of time. This is the inverse function of create. It also stores all the retrieved
72 * values in the default array
74 * @param array $params (reference ) an assoc array of name/value pairs
75 * @param array $defaults (reference ) an assoc array to hold the flattened values
77 * @return object CRM_Price_DAO_PriceSet object
81 static function retrieve(&$params, &$defaults) {
82 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
86 * update the is_active flag in the db
88 * @param int $id id of the database record
89 * @param boolean $is_active value we want to set the is_active field
91 * @return Object DAO object on sucess, null otherwise
95 static function setIsActive($id, $isActive) {
96 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
100 * Calculate the default price set id
101 * assigned to the contribution/membership etc
103 * @param string $entity
105 * @return id $priceSetID
111 public static function getDefaultPriceSet($entity = 'contribution') {
112 if ($entity == 'contribution') {
113 $entityName = 'default_contribution_amount';
115 else if ($entity == 'membership') {
116 $entityName = 'default_membership_type_amount';
120 SELECT ps.id AS setID, pfv.price_field_id AS priceFieldID, pfv.id AS priceFieldValueID, pfv.name, pfv.label
121 FROM civicrm_price_set ps
122 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
123 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
124 WHERE ps.name = '{$entityName}'
127 $dao = CRM_Core_DAO
::executeQuery($sql);
128 $defaultPriceSet = array();
129 while ($dao->fetch()) {
130 $defaultPriceSet[$dao->priceFieldValueID
]['setID'] = $dao->setID
;
131 $defaultPriceSet[$dao->priceFieldValueID
]['priceFieldID'] = $dao->priceFieldID
;
132 $defaultPriceSet[$dao->priceFieldValueID
]['name'] = $dao->name
;
133 $defaultPriceSet[$dao->priceFieldValueID
]['label'] = $dao->label
;
134 $defaultPriceSet[$dao->priceFieldValueID
]['priceFieldValueID'] = $dao->priceFieldValueID
;
137 return $defaultPriceSet;
141 * Get the price set title.
143 * @param int $id id of price set
145 * @return string title
151 public static function getTitle($id) {
152 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
156 * Return a list of all forms which use this price set.
158 * @param int $id id of price set
159 * @param str $simpleReturn - get raw data. Possible values: 'entity', 'table'
163 public static function &getUsedBy($id, $simpleReturn = FALSE) {
164 $usedBy = $forms = $tables = array();
166 SELECT entity_table, entity_id
167 FROM civicrm_price_set_entity
168 WHERE price_set_id = %1";
169 $params = array(1 => array($id, 'Integer'));
170 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
172 while ($crmFormDAO->fetch()) {
173 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
174 $tables[] = $crmFormDAO->entity_table
;
176 // Return only tables
177 if ($simpleReturn == 'table') {
182 SELECT cli.entity_table, cli.entity_id
183 FROM civicrm_line_item cli
184 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
185 WHERE cpf.price_set_id = %1";
186 $params = array(1 => array($id, 'Integer'));
187 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
188 while ($crmFormDAO->fetch()) {
189 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
190 $tables[] = $crmFormDAO->entity_table
;
196 // Return only entity data
197 if ($simpleReturn == 'entity') {
200 foreach ($forms as $table => $entities) {
202 case 'civicrm_event':
203 $ids = implode(',', $entities);
204 $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
205 FROM civicrm_event ce
206 LEFT JOIN civicrm_option_value ON
207 ( ce.event_type_id = civicrm_option_value.value )
208 LEFT JOIN civicrm_option_group ON
209 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
211 civicrm_option_group.name = 'event_type' AND
214 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
215 while ($crmDAO->fetch()) {
216 if ($crmDAO->isTemplate
) {
217 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
218 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
219 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
222 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
223 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
224 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
225 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
226 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
231 case 'civicrm_contribution_page':
232 $ids = implode(',', $entities);
233 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
234 FROM civicrm_contribution_page cp, civicrm_financial_type ct
235 WHERE ct.id = cp.financial_type_id AND
238 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
239 while ($crmDAO->fetch()) {
240 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
241 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
242 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
243 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
247 case 'civicrm_contribution':
248 case 'civicrm_membership':
249 case 'civicrm_participant':
254 CRM_Core_Error
::fatal("$table is not supported in PriceSet::usedBy()");
263 * Delete the price set
265 * @param int $id Price Set id
267 * @return boolean false if fields exist for this set, true if the
268 * set could be deleted
273 public static function deleteSet($id) {
274 // remove from all inactive forms
275 $usedBy = self
::getUsedBy($id);
276 if (isset($usedBy['civicrm_event'])) {
277 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
278 $eventDAO = new CRM_Event_DAO_Event();
279 $eventDAO->id
= $eventId;
281 while ($eventDAO->fetch()) {
282 self
::removeFrom('civicrm_event', $eventDAO->id
);
287 // delete price fields
288 $priceField = new CRM_Price_DAO_PriceField();
289 $priceField->price_set_id
= $id;
291 while ($priceField->fetch()) {
292 // delete options first
293 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
296 $set = new CRM_Price_DAO_PriceSet();
298 return $set->delete();
302 * Link the price set with the specified table and id
304 * @param string $entityTable
305 * @param integer $entityId
306 * @param integer $priceSetId
310 public static function addTo($entityTable, $entityId, $priceSetId) {
311 // verify that the price set exists
312 $dao = new CRM_Price_DAO_PriceSet();
313 $dao->id
= $priceSetId;
319 $dao = new CRM_Price_DAO_PriceSetEntity();
320 // find if this already exists
321 $dao->entity_id
= $entityId;
322 $dao->entity_table
= $entityTable;
325 // add or update price_set_id
326 $dao->price_set_id
= $priceSetId;
331 * Delete price set for the given entity and id
333 * @param string $entityTable
334 * @param integer $entityId
336 public static function removeFrom($entityTable, $entityId) {
337 $dao = new CRM_Price_DAO_PriceSetEntity();
338 $dao->entity_table
= $entityTable;
339 $dao->entity_id
= $entityId;
340 return $dao->delete();
344 * Find a price_set_id associatied with the given table, id and usedFor
345 * Used For value for events:1, contribution:2, membership:3
347 * @param string $entityTable
348 * @param int $entityId
349 * @param int $usedFor ( price set that extends/used for particular component )
351 * @return integer|false price_set_id, or false if none found
353 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
354 if (!$entityTable ||
!$entityId) {
358 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
359 FROM civicrm_price_set ps
360 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
361 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
362 if ($isQuickConfig) {
363 $sql .= ' AND ps.is_quick_config = 0 ';
365 $params = array(1 => array($entityTable, 'String'),
366 2 => array($entityId, 'Integer'),
369 $sql .= " AND ps.extends LIKE '%%3%' ";
370 $params[3] = array($usedFor, 'Integer');
373 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
375 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
376 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
380 * Find a price_set_id associatied with the given option value or field ID
382 * @param array $params (reference) an assoc array of name/value pairs
383 * array may contain either option id or
386 * @return price set id on success, null otherwise
390 public static function getSetId(&$params) {
393 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
394 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
395 $fieldValue->id
= $oid;
396 if ($fieldValue->find(TRUE)) {
397 $fid = $fieldValue->price_field_id
;
401 $fid = CRM_Utils_Array
::value('fid', $params);
405 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
412 * Return an associative array of all price sets
414 * @param bool $withInactive whether or not to include inactive entries
415 * @param string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
417 * @return array associative array of id => name
419 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE) {
422 DISTINCT ( price_set_id ) as id, title
427 civicrm_price_set.id = civicrm_price_field.price_set_id AND is_quick_config = 0 ';
429 if (!$withInactive) {
430 $query .= ' AND civicrm_price_set.is_active = 1 ';
433 if (self
::eventPriceSetDomainID()) {
434 $query .= ' AND civicrm_price_set.domain_id = ' . CRM_Core_Config
::domainID();
437 $priceSets = array();
439 if ($extendComponentName) {
440 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
444 $query .= " AND civicrm_price_set.extends LIKE '%$componentId%' ";
447 $dao = CRM_Core_DAO
::executeQuery($query);
448 while ($dao->fetch()) {
449 $priceSets[$dao->id
] = $dao->title
;
455 * Get price set details
457 * An array containing price set details (including price fields) is returned
459 * @param int $setId - price set id whose details are needed
461 * @return array $setTree - array consisting of field details
463 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
466 $select = $from = $where = $orderBy = '';
468 $priceFields = array(
477 'is_display_amounts',
486 if ($required == TRUE) {
487 $priceFields[] = 'is_required';
491 $select = 'SELECT ' . implode(',', $priceFields);
492 $from = ' FROM civicrm_price_field';
495 $params[1] = array($setID, 'Integer');
497 WHERE price_set_id = %1
502 $currentTime = date('YmdHis');
504 AND ( active_on IS NULL OR active_on <= {$currentTime} )
505 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
509 $orderBy = ' ORDER BY weight';
511 $sql = $select . $from . $where . $dateSelect . $orderBy;
513 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
515 $visibility = CRM_Core_PseudoConstant
::visibility('name');
516 while ($dao->fetch()) {
519 $setTree[$setID]['fields'][$fieldID] = array();
520 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
522 foreach ($priceFields as $field) {
523 if ($field == 'id' ||
is_null($dao->$field)) {
527 if ($field == 'visibility_id') {
528 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
530 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
532 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE);
535 // also get the pre and post help from this price set
537 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
538 FROM civicrm_price_set
540 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
542 $setTree[$setID]['extends'] = $dao->extends;
543 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
544 $setTree[$setID]['help_pre'] = $dao->help_pre
;
545 $setTree[$setID]['help_post'] = $dao->help_post
;
546 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
551 static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
553 $priceSetId = self
::getFor($entityTable, $id);
556 //check if priceset is is_config
557 if (is_numeric($priceSetId)) {
558 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
559 $form->assign('quickConfig', 1);
564 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
565 $entityId = $entity = NULL;
567 switch ($entityTable) {
568 case 'civicrm_event':
569 $entity = 'participant';
570 if (CRM_Utils_System
::getClassName($form) == 'CRM_Event_Form_Participant') {
571 $entityId = $form->_id
;
574 $entityId = $form->_participantId
;
578 case 'civicrm_contribution_page':
579 case 'civicrm_contribution':
580 $entity = 'contribution';
581 $entityId = $form->_id
;
585 if ($entityId && $entity) {
586 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
594 $form->_priceSetId
= $priceSetId;
595 $priceSet = self
::getSetDetail($priceSetId, $required, $validOnly);
596 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
597 $form->_values
['fee'] = CRM_Utils_Array
::value('fields', $form->_priceSet
);
599 //get the price set fields participant count.
600 if ($entityTable == 'civicrm_event') {
601 //get option count info.
602 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
603 if ($form->_priceSet
['optionsCountTotal']) {
604 $optionsCountDeails = array();
605 if (!empty($form->_priceSet
['fields'])) {
606 foreach ($form->_priceSet
['fields'] as $field) {
607 foreach ($field['options'] as $option) {
608 $count = CRM_Utils_Array
::value('count', $option, 0);
609 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
613 $form->_priceSet
['optionsCountDetails'] = $optionsCountDeails;
616 //get option max value info.
617 $optionsMaxValueTotal = 0;
618 $optionsMaxValueDetails = array();
620 if (!empty($form->_priceSet
['fields'])) {
621 foreach ($form->_priceSet
['fields'] as $field) {
622 foreach ($field['options'] as $option) {
623 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
624 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
625 $optionsMaxValueTotal +
= $maxVal;
630 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
631 if ($optionsMaxValueTotal) {
632 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
635 $form->set('priceSetId', $form->_priceSetId
);
636 $form->set('priceSet', $form->_priceSet
);
643 static function processAmount(&$fields, &$params, &$lineItem, $component = '') {
646 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
648 $autoRenew = array();
649 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
651 foreach ($fields as $id => $field) {
652 if (empty($params["price_{$id}"]) ||
653 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
655 // skip if nothing was submitted for this field
659 switch ($field['html_type']) {
661 $params["price_{$id}"] = array(key($field['options']) => $params["price_{$id}"]);
662 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
663 $totalPrice +
= $lineItem[key($field['options'])]['line_total'];
667 //special case if user select -none-
668 if ($params["price_{$id}"] <= 0) {
671 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
672 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
673 $optionLabel = CRM_Utils_Array
::value('label', $field['options'][$optionValueId]);
674 $params['amount_priceset_level_radio'] = array();
675 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
676 if (isset($radioLevel)) {
677 $radioLevel = array_merge($radioLevel,
678 array_keys($params['amount_priceset_level_radio'])
682 $radioLevel = array_keys($params['amount_priceset_level_radio']);
684 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
685 $totalPrice +
= $lineItem[$optionValueId]['line_total'];
688 // auto_renew exists and is empty in some workflows, which php treat as a 0
689 // and hence we explicity check to see if auto_renew is numeric
690 isset($lineItem[$optionValueId]['auto_renew']) &&
691 is_numeric($lineItem[$optionValueId]['auto_renew'])
693 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
698 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
699 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
700 $optionLabel = $field['options'][$optionValueId]['label'];
701 $params['amount_priceset_level_select'] = array();
702 $params['amount_priceset_level_select'][CRM_Utils_Array
::key(1, $params["price_{$id}"])] = $optionLabel;
703 if (isset($selectLevel)) {
704 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
707 $selectLevel = array_keys($params['amount_priceset_level_select']);
709 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
710 $totalPrice +
= $lineItem[$optionValueId]['line_total'];
713 isset($lineItem[$optionValueId]['auto_renew']) &&
714 is_numeric($lineItem[$optionValueId]['auto_renew'])
716 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
721 $params['amount_priceset_level_checkbox'] = $optionIds = array();
722 foreach ($params["price_{$id}"] as $optionId => $option) {
723 $optionIds[] = $optionId;
724 $optionLabel = $field['options'][$optionId]['label'];
725 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
726 if (isset($checkboxLevel)) {
727 $checkboxLevel = array_unique(array_merge(
729 array_keys($params['amount_priceset_level_checkbox'])
734 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
737 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
738 foreach ($optionIds as $optionId) {
739 $totalPrice +
= $lineItem[$optionId]['line_total'];
742 isset($lineItem[$optionId]['auto_renew']) &&
743 is_numeric($lineItem[$optionId]['auto_renew'])
745 $autoRenew[$lineItem[$optionId]['auto_renew']] +
= $lineItem[$optionId]['line_total'];
752 $amount_level = array();
753 $totalParticipant = 0;
754 if (is_array($lineItem)) {
755 foreach ($lineItem as $values) {
756 $totalParticipant +
= $values['participant_count'];
757 if ($values['html_type'] == 'Text') {
758 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
761 $amount_level[] = $values['label'];
765 $displayParticipantCount = '';
766 if ($totalParticipant > 0) {
767 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
769 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
770 $params['amount'] = $totalPrice;
772 foreach ($autoRenew as $dontCare => $eachAmount) {
774 unset($autoRenew[$dontCare]);
777 if (count($autoRenew) > 1 ) {
778 $params['autoRenew'] = $autoRenew;
784 * Function to build the price set form.
789 static function buildPriceSet(&$form) {
790 $priceSetId = $form->get('priceSetId');
791 $userid = $form->getVar('_userID');
796 $validFieldsOnly = TRUE;
797 $className = CRM_Utils_System
::getClassName($form);
798 if (in_array($className, array(
799 'CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'))) {
800 $validFieldsOnly = FALSE;
803 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
804 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
805 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
806 $form->_quickConfig
= $quickConfig = 0;
807 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
811 $form->assign('quickConfig', $quickConfig);
812 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
813 $form->_quickConfig
= $quickConfig;
815 $form->assign('priceSet', $form->_priceSet
);
817 $component = 'contribution';
818 if ($className == 'CRM_Member_Form_Membership') {
819 $component = 'membership';
822 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
823 $feeBlock = &$form->_values
['fee'];
824 if (!empty($form->_useForMember
)) {
825 $component = 'membership';
829 $feeBlock = &$form->_priceSet
['fields'];
833 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
835 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
836 $adminFieldVisible = false;
837 if (CRM_Core_Permission
::check('administer CiviCRM')) {
838 $adminFieldVisible = true;
841 foreach ($feeBlock as $id => $field) {
842 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
843 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == true) ||
846 $options = CRM_Utils_Array
::value('options', $field);
847 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
848 $checklifetime = self
::checkCurrentMembership($options, $userid);
849 if ($checklifetime) {
850 $form->assign('ispricelifetime', TRUE);
853 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
856 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
857 'price_' . $field['id'],
860 CRM_Utils_Array
::value('is_required', $field, FALSE),
869 * Function to check the current Membership
870 * having end date null.
872 static function checkCurrentMembership(&$options, $userid) {
873 if (!$userid ||
empty($options)) {
876 static $_contact_memberships = array();
877 $checklifetime = FALSE;
878 foreach ($options as $key => $value) {
879 if (!empty($value['membership_type_id'])) {
880 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
881 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
883 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
884 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
885 unset($options[$key]);
886 $checklifetime = TRUE;
890 if ($checklifetime) {
899 * Function to set daefult the price set fields.
901 * @return array $defaults
904 static function setDefaultPriceSet(&$form, &$defaults) {
905 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
909 foreach ($form->_priceSet
['fields'] as $key => $val) {
910 foreach ($val['options'] as $keys => $values) {
911 if ($values['is_default']) {
912 if ($val['html_type'] == 'CheckBox') {
913 $defaults["price_{$key}"][$keys] = 1;
916 $defaults["price_{$key}"] = $keys;
925 * Get field ids of a price set
927 * @param int id Price Set id
929 * @return array of the field ids
934 public static function getFieldIds($id) {
935 $priceField = new CRM_Price_DAO_PriceField();
936 $priceField->price_set_id
= $id;
938 while ($priceField->fetch()) {
939 $var[] = $priceField->id
;
945 * This function is to make a copy of a price set, including
948 * @param int $id the price set id to copy
950 * @return the copy object
954 static function copy($id) {
955 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
957 $title = ts('[Copy id %1]', array(1 => $maxId +
1));
959 'suffix' => array('title' => ' ' . $title,
960 'name' => '__Copy_id_' . ($maxId +
1) . '_',
964 $copy = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
970 //copying all the blocks pertaining to the price set
971 $copyPriceField = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
972 array('price_set_id' => $id),
973 array('price_set_id' => $copy->id
)
975 if (!empty($copyPriceField)) {
976 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
978 //copy option group and values
979 foreach ($price as $originalId => $copyId) {
980 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
981 array('price_field_id' => $originalId),
982 array('price_field_id' => $copyId)
988 CRM_Utils_Hook
::copy('Set', $copy);
993 * This function is to check price set permission
995 * @param int $sid the price set id
997 static function checkPermission($sid) {
998 if ($sid && self
::eventPriceSetDomainID()) {
999 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1000 if (CRM_Core_Config
::domainID() != $domain_id) {
1001 CRM_Core_Error
::fatal(ts('You do not have permission to access this page'));
1008 * Get the sum of participant count
1009 * for all fields of given price set.
1011 * @param int $sid the price set id
1016 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1024 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1027 static $pricesetFieldCount = array();
1028 if (!isset($pricesetFieldCount[$sid])) {
1030 SELECT sum(value.count) as totalCount
1031 FROM civicrm_price_field_value value
1032 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1033 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1037 $count = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1038 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1041 return $pricesetFieldCount[$sid];
1044 public static function getMembershipCount($ids) {
1046 SELECT count( pfv.id ) AS count, pfv.id AS id
1047 FROM civicrm_price_field_value pfv
1048 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1049 WHERE pfv.id IN ( $ids )
1050 GROUP BY mt.member_of_contact_id";
1052 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1055 while ($crmDAO->fetch()) {
1056 $count[$crmDAO->id
] = $crmDAO->count
;
1063 * Function to check if auto renew option should be shown
1065 * @param int $priceSetId price set id
1067 * @return int $autoRenewOption ( 0:hide, 1:optional 2:required )
1069 public static function checkAutoRenewForPriceSet($priceSetId) {
1070 // auto-renew option should be visible if membership types associated with all the fields has
1071 // been set for auto-renew option
1072 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1074 // get the membership type auto renew option and check if required or optional
1075 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1076 FROM civicrm_price_field_value pfv
1077 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1078 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1079 WHERE pf.price_set_id = %1
1080 AND pf.is_active = 1
1081 AND pfv.is_active = 1';
1083 $params = array(1 => array($priceSetId, 'Integer'));
1085 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1086 $autoRenewOption = 2;
1087 $interval = $unit = array();
1088 while ($dao->fetch()) {
1089 if (!$dao->auto_renew
) {
1090 $autoRenewOption = 0;
1093 if ($dao->auto_renew
== 1) {
1094 $autoRenewOption = 1;
1097 $interval[$dao->duration_interval
] = $dao->duration_interval
;
1098 $unit[$dao->duration_unit
] = $dao->duration_unit
;
1101 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1102 return $autoRenewOption;
1110 * Function to retrieve auto renew frequency and interval
1112 * @param int $priceSetId price set id
1114 * @return array associate array of frequency interval and unit
1118 public static function getRecurDetails($priceSetId) {
1119 $query = 'SELECT mt.duration_interval, mt.duration_unit
1120 FROM civicrm_price_field_value pfv
1121 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1122 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1123 WHERE pf.price_set_id = %1 LIMIT 1';
1125 $params = array(1 => array($priceSetId, 'Integer'));
1126 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1128 return array($dao->duration_interval
, $dao->duration_unit
);
1131 static function eventPriceSetDomainID() {
1132 return CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
1133 'event_price_set_domain_id',
1139 * update the is_quick_config flag in the db
1141 * @param int $id id of the database record
1142 * @param boolean $isQuickConfig value we want to set the is_quick_config field
1144 * @return Object DAO object on sucess, null otherwise
1148 static function setIsQuickConfig($id, $isQuickConfig) {
1149 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1153 * Check if price set id provides option for
1154 * user to select both auto-renew and non-auto-renew memberships
1160 public static function checkMembershipPriceSet($id) {
1163 SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1164 FROM civicrm_price_field_value pfv
1165 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1166 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1167 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1171 $params = array(1 => array($id, 'Integer'));
1172 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1174 $autoRenew = array();
1175 //FIXME: do a comprehensive check of whether
1176 //2 membership types can be selected
1177 //instead of comparing all of them
1178 while ($dao->fetch()) {
1179 //temp fix for #CRM-10370
1180 //if its NULL consider it '0' i.e. 'No auto-renew option'
1181 $daoAutoRenew = $dao->auto_renew
;
1182 if ($daoAutoRenew === NULL) {
1185 if (!empty($autoRenew) && !in_array($daoAutoRenew, $autoRenew)) {
1188 $autoRenew[] = $daoAutoRenew;
1194 * Copy priceSet when event/contibution page is copied
1196 * @params string $baoName BAO name
1197 * @params int $id old event/contribution page id
1198 * @params int $newId newly created event/contribution page id
1201 static function copyPriceSet($baoName, $id, $newId) {
1202 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1204 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1205 if($isQuickConfig) {
1206 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($priceSetId);
1207 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1210 $copyPriceSet = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1213 'entity_table' => $baoName,
1215 array('entity_id' => $newId)
1218 // copy event discount
1219 if ($baoName == 'civicrm_event') {
1220 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1221 foreach ($discount as $discountId => $setId) {
1223 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1225 $copyDiscount = &CRM_Core_DAO
::copyGeneric(
1226 'CRM_Core_DAO_Discount',
1228 'id' => $discountId,
1231 'entity_id' => $newId,
1232 'price_set_id' => $copyPriceSet->id
,