Merge pull request #4252 from civicrm/4.4
[civicrm-core.git] / CRM / Price / BAO / PriceSet.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * Business object for managing price sets
38 *
39 */
40 class CRM_Price_BAO_PriceSet extends CRM_Price_DAO_PriceSet {
41
42
43 /**
44 * static field for default price set details
45 *
46 * @var array
47 * @static
48 */
49 static $_defaultPriceSet = NULL;
50
51 /**
52 * class constructor
53 */
54 function __construct() {
55 parent::__construct();
56 }
57
58 /**
59 * takes an associative array and creates a price set object
60 *
61 * @param array $params (reference) an assoc array of name/value pairs
62 *
63 * @return object CRM_Price_DAO_PriceSet object
64 * @access public
65 * @static
66 */
67 static function create(&$params) {
68 if(empty($params['id']) && empty($params['name'])) {
69 $params['name'] = CRM_Utils_String::munge($params['title'], '_', 242);
70 }
71 $priceSetBAO = new CRM_Price_BAO_PriceSet();
72 $priceSetBAO->copyValues($params);
73 if (self::eventPriceSetDomainID()) {
74 $priceSetBAO->domain_id = CRM_Core_Config::domainID();
75 }
76 return $priceSetBAO->save();
77 }
78
79 /**
80 * Takes a bunch of params that are needed to match certain criteria and
81 * retrieves the relevant objects. Typically the valid params are only
82 * contact_id. We'll tweak this function to be more full featured over a period
83 * of time. This is the inverse function of create. It also stores all the retrieved
84 * values in the default array
85 *
86 * @param array $params (reference ) an assoc array of name/value pairs
87 * @param array $defaults (reference ) an assoc array to hold the flattened values
88 *
89 * @return object CRM_Price_DAO_PriceSet object
90 * @access public
91 * @static
92 */
93 static function retrieve(&$params, &$defaults) {
94 return CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
95 }
96
97 /**
98 * update the is_active flag in the db
99 *
100 * @param int $id id of the database record
101 * @param $isActive
102 *
103 * @internal param bool $is_active value we want to set the is_active field
104 *
105 * @return Object DAO object on sucess, null otherwise
106 * @static
107 * @access public
108 */
109 static function setIsActive($id, $isActive) {
110 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
111 }
112
113 /**
114 * Calculate the default price set id
115 * assigned to the contribution/membership etc
116 *
117 * @param string $entity
118 *
119 * @return array $defaultPriceSet default price set
120 *
121 * @access public
122 * @static
123 *
124 */
125 public static function getDefaultPriceSet($entity = 'contribution') {
126 if (!empty(self::$_defaultPriceSet[$entity])) {
127 return self::$_defaultPriceSet[$entity];
128 }
129 $entityName = 'default_contribution_amount';
130 if ($entity == 'membership') {
131 $entityName = 'default_membership_type_amount';
132 }
133
134 $sql = "
135 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
136 FROM civicrm_price_set ps
137 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
138 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
139 WHERE ps.name = '{$entityName}'
140 ";
141
142 $dao = CRM_Core_DAO::executeQuery($sql);
143 self::$_defaultPriceSet[$entity] = array();
144 while ($dao->fetch()) {
145 self::$_defaultPriceSet[$entity][$dao->priceFieldValueID] = array(
146 'setID' => $dao->setID,
147 'priceFieldID' => $dao->priceFieldID,
148 'name' => $dao->name,
149 'label' => $dao->label,
150 'priceFieldValueID' => $dao->priceFieldValueID,
151 'membership_type_id' => $dao->membership_type_id,
152 'amount' => $dao->amount,
153 'financial_type_id' => $dao->financial_type_id,
154 );
155 }
156
157 return self::$_defaultPriceSet[$entity];
158 }
159
160 /**
161 * Get the price set title.
162 *
163 * @param int $id id of price set
164 *
165 * @return string title
166 *
167 * @access public
168 * @static
169 *
170 */
171 public static function getTitle($id) {
172 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
173 }
174
175 /**
176 * Return a list of all forms which use this price set.
177 *
178 * @param int $id id of price set
179 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
180 *
181 * @return array
182 */
183 public static function &getUsedBy($id, $simpleReturn = FALSE) {
184 $usedBy = $forms = $tables = array();
185 $queryString = "
186 SELECT entity_table, entity_id
187 FROM civicrm_price_set_entity
188 WHERE price_set_id = %1";
189 $params = array(1 => array($id, 'Integer'));
190 $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
191
192 while ($crmFormDAO->fetch()) {
193 $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
194 $tables[] = $crmFormDAO->entity_table;
195 }
196 // Return only tables
197 if ($simpleReturn == 'table') {
198 return $tables;
199 }
200 if (empty($forms)) {
201 $queryString = "
202 SELECT cli.entity_table, cli.entity_id
203 FROM civicrm_line_item cli
204 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
205 WHERE cpf.price_set_id = %1";
206 $params = array(1 => array($id, 'Integer'));
207 $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
208 while ($crmFormDAO->fetch()) {
209 $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
210 $tables[] = $crmFormDAO->entity_table;
211 }
212 if (empty($forms)) {
213 return $usedBy;
214 }
215 }
216 // Return only entity data
217 if ($simpleReturn == 'entity') {
218 return $forms;
219 }
220 foreach ($forms as $table => $entities) {
221 switch ($table) {
222 case 'civicrm_event':
223 $ids = implode(',', $entities);
224 $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
225 FROM civicrm_event ce
226 LEFT JOIN civicrm_option_value ON
227 ( ce.event_type_id = civicrm_option_value.value )
228 LEFT JOIN civicrm_option_group ON
229 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
230 WHERE
231 civicrm_option_group.name = 'event_type' AND
232 ce.id IN ($ids) AND
233 ce.is_active = 1;";
234 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
235 while ($crmDAO->fetch()) {
236 if ($crmDAO->isTemplate) {
237 $usedBy['civicrm_event_template'][$crmDAO->id]['title'] = $crmDAO->templateTitle;
238 $usedBy['civicrm_event_template'][$crmDAO->id]['eventType'] = $crmDAO->eventType;
239 $usedBy['civicrm_event_template'][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
240 }
241 else {
242 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
243 $usedBy[$table][$crmDAO->id]['eventType'] = $crmDAO->eventType;
244 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
245 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
246 $usedBy[$table][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
247 }
248 }
249 break;
250
251 case 'civicrm_contribution_page':
252 $ids = implode(',', $entities);
253 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
254 FROM civicrm_contribution_page cp, civicrm_financial_type ct
255 WHERE ct.id = cp.financial_type_id AND
256 cp.id IN ($ids) AND
257 cp.is_active = 1;";
258 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
259 while ($crmDAO->fetch()) {
260 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
261 $usedBy[$table][$crmDAO->id]['type'] = $crmDAO->type;
262 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
263 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
264 }
265 break;
266
267 case 'civicrm_contribution':
268 case 'civicrm_membership':
269 case 'civicrm_participant':
270 $usedBy[$table] = 1;
271 break;
272
273 default:
274 CRM_Core_Error::fatal("$table is not supported in PriceSet::usedBy()");
275 break;
276 }
277 }
278
279 return $usedBy;
280 }
281
282 /**
283 * Delete the price set
284 *
285 * @param int $id Price Set id
286 *
287 * @return boolean false if fields exist for this set, true if the
288 * set could be deleted
289 *
290 * @access public
291 * @static
292 */
293 public static function deleteSet($id) {
294 // remove from all inactive forms
295 $usedBy = self::getUsedBy($id);
296 if (isset($usedBy['civicrm_event'])) {
297 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
298 $eventDAO = new CRM_Event_DAO_Event();
299 $eventDAO->id = $eventId;
300 $eventDAO->find();
301 while ($eventDAO->fetch()) {
302 self::removeFrom('civicrm_event', $eventDAO->id);
303 }
304 }
305 }
306
307 // delete price fields
308 $priceField = new CRM_Price_DAO_PriceField();
309 $priceField->price_set_id = $id;
310 $priceField->find();
311 while ($priceField->fetch()) {
312 // delete options first
313 CRM_Price_BAO_PriceField::deleteField($priceField->id);
314 }
315
316 $set = new CRM_Price_DAO_PriceSet();
317 $set->id = $id;
318 return $set->delete();
319 }
320
321 /**
322 * Link the price set with the specified table and id
323 *
324 * @param string $entityTable
325 * @param integer $entityId
326 * @param integer $priceSetId
327 *
328 * @return bool
329 */
330 public static function addTo($entityTable, $entityId, $priceSetId) {
331 // verify that the price set exists
332 $dao = new CRM_Price_DAO_PriceSet();
333 $dao->id = $priceSetId;
334 if (!$dao->find()) {
335 return FALSE;
336 }
337 unset($dao);
338
339 $dao = new CRM_Price_DAO_PriceSetEntity();
340 // find if this already exists
341 $dao->entity_id = $entityId;
342 $dao->entity_table = $entityTable;
343 $dao->find(TRUE);
344
345 // add or update price_set_id
346 $dao->price_set_id = $priceSetId;
347 return $dao->save();
348 }
349
350 /**
351 * Delete price set for the given entity and id
352 *
353 * @param string $entityTable
354 * @param integer $entityId
355 *
356 * @return mixed
357 */
358 public static function removeFrom($entityTable, $entityId) {
359 $dao = new CRM_Price_DAO_PriceSetEntity();
360 $dao->entity_table = $entityTable;
361 $dao->entity_id = $entityId;
362 return $dao->delete();
363 }
364
365 /**
366 * Find a price_set_id associatied with the given table, id and usedFor
367 * Used For value for events:1, contribution:2, membership:3
368 *
369 * @param string $entityTable
370 * @param int $entityId
371 * @param int $usedFor ( price set that extends/used for particular component )
372 *
373 * @param null $isQuickConfig
374 * @param null $setName
375 *
376 * @return integer|false price_set_id, or false if none found
377 */
378 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
379 if (!$entityTable || !$entityId) {
380 return FALSE;
381 }
382
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 ';
389 }
390 $params = array(1 => array($entityTable, 'String'),
391 2 => array($entityId, 'Integer'),
392 );
393 if ($usedFor) {
394 $sql .= " AND ps.extends LIKE '%%3%' ";
395 $params[3] = array($usedFor, 'Integer');
396 }
397
398 $dao = CRM_Core_DAO::executeQuery($sql, $params);
399 $dao->fetch();
400 $setName = (isset($dao->price_set_name)) ? $dao->price_set_name : FALSE;
401 return (isset($dao->price_set_id)) ? $dao->price_set_id : FALSE;
402 }
403
404 /**
405 * Find a price_set_id associated with the given option value or field ID
406 *
407 * @param array $params (reference) an assoc array of name/value pairs
408 * array may contain either option id or
409 * price field id
410 *
411 * @return integer|NULL price set id on success, null otherwise
412 * @static
413 * @access public
414 */
415 public static function getSetId(&$params) {
416 $fid = NULL;
417
418 if ($oid = CRM_Utils_Array::value('oid', $params)) {
419 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
420 $fieldValue->id = $oid;
421 if ($fieldValue->find(TRUE)) {
422 $fid = $fieldValue->price_field_id;
423 }
424 }
425 else {
426 $fid = CRM_Utils_Array::value('fid', $params);
427 }
428
429 if (isset($fid)) {
430 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
431 }
432
433 return NULL;
434 }
435
436 /**
437 * Return an associative array of all price sets
438 *
439 * @param bool $withInactive whether or not to include inactive entries
440 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
441 *
442 * @return array associative array of id => name
443 */
444 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE) {
445 $query = '
446 SELECT
447 DISTINCT ( price_set_id ) as id, title
448 FROM
449 civicrm_price_field,
450 civicrm_price_set
451 WHERE
452 civicrm_price_set.id = civicrm_price_field.price_set_id AND is_quick_config = 0 ';
453
454 if (!$withInactive) {
455 $query .= ' AND civicrm_price_set.is_active = 1 ';
456 }
457
458 if (self::eventPriceSetDomainID()) {
459 $query .= ' AND civicrm_price_set.domain_id = ' . CRM_Core_Config::domainID();
460 }
461
462 $priceSets = array();
463
464 if ($extendComponentName) {
465 $componentId = CRM_Core_Component::getComponentID($extendComponentName);
466 if (!$componentId) {
467 return $priceSets;
468 }
469 $query .= " AND civicrm_price_set.extends LIKE '%$componentId%' ";
470 }
471
472 $dao = CRM_Core_DAO::executeQuery($query);
473 while ($dao->fetch()) {
474 $priceSets[$dao->id] = $dao->title;
475 }
476 return $priceSets;
477 }
478
479 /**
480 * Get price set details
481 *
482 * An array containing price set details (including price fields) is returned
483 *
484 * @param $setID
485 * @param bool $required
486 * @param bool $validOnly
487 *
488 * @internal param int $setId - price set id whose details are needed
489 *
490 * @return array $setTree - array consisting of field details
491 */
492 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
493 // create a new tree
494 $setTree = array();
495
496 $priceFields = array(
497 'id',
498 'name',
499 'label',
500 'html_type',
501 'is_enter_qty',
502 'help_pre',
503 'help_post',
504 'weight',
505 'is_display_amounts',
506 'options_per_line',
507 'is_active',
508 'active_on',
509 'expire_on',
510 'javascript',
511 'visibility_id',
512 'is_required',
513 );
514 if ($required == TRUE) {
515 $priceFields[] = 'is_required';
516 }
517
518 // create select
519 $select = 'SELECT ' . implode(',', $priceFields);
520 $from = ' FROM civicrm_price_field';
521
522 $params = array();
523 $params[1] = array($setID, 'Integer');
524 $where = '
525 WHERE price_set_id = %1
526 AND is_active = 1
527 ';
528 $dateSelect = '';
529 if ($validOnly) {
530 $currentTime = date('YmdHis');
531 $dateSelect = "
532 AND ( active_on IS NULL OR active_on <= {$currentTime} )
533 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
534 ";
535 }
536
537 $orderBy = ' ORDER BY weight';
538
539 $sql = $select . $from . $where . $dateSelect . $orderBy;
540
541 $dao = CRM_Core_DAO::executeQuery($sql, $params);
542
543 $visibility = CRM_Core_PseudoConstant::visibility('name');
544 while ($dao->fetch()) {
545 $fieldID = $dao->id;
546
547 $setTree[$setID]['fields'][$fieldID] = array();
548 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
549
550 foreach ($priceFields as $field) {
551 if ($field == 'id' || is_null($dao->$field)) {
552 continue;
553 }
554
555 if ($field == 'visibility_id') {
556 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
557 }
558 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
559 }
560 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField::getOptions($fieldID, FALSE);
561 }
562
563 // also get the pre and post help from this price set
564 $sql = "
565 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
566 FROM civicrm_price_set
567 WHERE id = %1";
568 $dao = CRM_Core_DAO::executeQuery($sql, $params);
569 if ($dao->fetch()) {
570 $setTree[$setID]['extends'] = $dao->extends;
571 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id;
572 $setTree[$setID]['help_pre'] = $dao->help_pre;
573 $setTree[$setID]['help_post'] = $dao->help_post;
574 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config;
575 }
576 return $setTree;
577 }
578
579 /**
580 * Get the Price Field ID. We call this function when more than one being present would represent an error
581 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
582 * @param array $priceSet
583 *
584 * @throws CRM_Core_Exception
585 * @return int
586 */
587 static function getOnlyPriceFieldID(array $priceSet) {
588 if(count($priceSet['fields']) > 1) {
589 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
590 }
591 return (int) implode('_', array_keys($priceSet['fields']));
592 }
593
594 /**
595 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
596 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
597 * @param array $priceSet
598 *
599 * @throws CRM_Core_Exception
600 * @return int
601 */
602 static function getOnlyPriceFieldValueID(array $priceSet) {
603 $priceFieldID = self::getOnlyPriceFieldID($priceSet);
604 if(count($priceSet['fields'][$priceFieldID]['options']) > 1) {
605 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
606 }
607 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
608 }
609
610
611 /**
612 * @param CRM_Core_Form $form
613 * @param $id
614 * @param string $entityTable
615 * @param bool $validOnly
616 * @param null $priceSetId
617 *
618 * @return bool|false|int|null
619 */
620 static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
621 if (!$priceSetId) {
622 $priceSetId = self::getFor($entityTable, $id);
623 }
624
625 //check if priceset is is_config
626 if (is_numeric($priceSetId)) {
627 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
628 $form->assign('quickConfig', 1);
629 }
630 }
631 // get price info
632 if ($priceSetId) {
633 if ($form->_action & CRM_Core_Action::UPDATE) {
634 $entityId = $entity = NULL;
635
636 switch ($entityTable) {
637 case 'civicrm_event':
638 $entity = 'participant';
639 if (CRM_Utils_System::getClassName($form) == 'CRM_Event_Form_Participant') {
640 $entityId = $form->_id;
641 }
642 else {
643 $entityId = $form->_participantId;
644 }
645 break;
646
647 case 'civicrm_contribution_page':
648 case 'civicrm_contribution':
649 $entity = 'contribution';
650 $entityId = $form->_id;
651 break;
652 }
653
654 if ($entityId && $entity) {
655 $form->_values['line_items'] = CRM_Price_BAO_LineItem::getLineItems($entityId, $entity);
656 }
657 $required = FALSE;
658 }
659 else {
660 $required = TRUE;
661 }
662
663 $form->_priceSetId = $priceSetId;
664 $priceSet = self::getSetDetail($priceSetId, $required, $validOnly);
665 $form->_priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
666 $form->_values['fee'] = CRM_Utils_Array::value('fields', $form->_priceSet);
667
668 //get the price set fields participant count.
669 if ($entityTable == 'civicrm_event') {
670 //get option count info.
671 $form->_priceSet['optionsCountTotal'] = self::getPricesetCount($priceSetId);
672 if ($form->_priceSet['optionsCountTotal']) {
673 $optionsCountDeails = array();
674 if (!empty($form->_priceSet['fields'])) {
675 foreach ($form->_priceSet['fields'] as $field) {
676 foreach ($field['options'] as $option) {
677 $count = CRM_Utils_Array::value('count', $option, 0);
678 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
679 }
680 }
681 }
682 $form->_priceSet['optionsCountDetails'] = $optionsCountDeails;
683 }
684
685 //get option max value info.
686 $optionsMaxValueTotal = 0;
687 $optionsMaxValueDetails = array();
688
689 if (!empty($form->_priceSet['fields'])) {
690 foreach ($form->_priceSet['fields'] as $field) {
691 foreach ($field['options'] as $option) {
692 $maxVal = CRM_Utils_Array::value('max_value', $option, 0);
693 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
694 $optionsMaxValueTotal += $maxVal;
695 }
696 }
697 }
698
699 $form->_priceSet['optionsMaxValueTotal'] = $optionsMaxValueTotal;
700 if ($optionsMaxValueTotal) {
701 $form->_priceSet['optionsMaxValueDetails'] = $optionsMaxValueDetails;
702 }
703 }
704 $form->set('priceSetId', $form->_priceSetId);
705 $form->set('priceSet', $form->_priceSet);
706
707 return $priceSetId;
708 }
709 return FALSE;
710 }
711
712 /**
713 * @param $fields
714 * @param $params
715 * @param $lineItem
716 * @param string $component
717 */
718 static function processAmount(&$fields, &$params, &$lineItem, $component = '') {
719 // using price set
720 $totalPrice = 0;
721 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
722 if ($component) {
723 $autoRenew = array();
724 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
725 }
726 foreach ($fields as $id => $field) {
727 if (empty($params["price_{$id}"]) ||
728 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
729 ) {
730 // skip if nothing was submitted for this field
731 continue;
732 }
733
734 switch ($field['html_type']) {
735 case 'Text':
736 $firstOption = reset($field['options']);
737 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
738 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
739 $totalPrice += $lineItem[$firstOption['id']]['line_total'];
740 break;
741
742 case 'Radio':
743 //special case if user select -none-
744 if ($params["price_{$id}"] <= 0) {
745 continue;
746 }
747 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
748 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
749 $optionLabel = CRM_Utils_Array::value('label', $field['options'][$optionValueId]);
750 $params['amount_priceset_level_radio'] = array();
751 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
752 if (isset($radioLevel)) {
753 $radioLevel = array_merge($radioLevel,
754 array_keys($params['amount_priceset_level_radio'])
755 );
756 }
757 else {
758 $radioLevel = array_keys($params['amount_priceset_level_radio']);
759 }
760 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
761 $totalPrice += $lineItem[$optionValueId]['line_total'];
762 if (
763 $component &&
764 // auto_renew exists and is empty in some workflows, which php treat as a 0
765 // and hence we explicitly check to see if auto_renew is numeric
766 isset($lineItem[$optionValueId]['auto_renew']) &&
767 is_numeric($lineItem[$optionValueId]['auto_renew'])
768 ) {
769 $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
770 }
771 break;
772
773 case 'Select':
774 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
775 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
776 $optionLabel = $field['options'][$optionValueId]['label'];
777 $params['amount_priceset_level_select'] = array();
778 $params['amount_priceset_level_select'][CRM_Utils_Array::key(1, $params["price_{$id}"])] = $optionLabel;
779 if (isset($selectLevel)) {
780 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
781 }
782 else {
783 $selectLevel = array_keys($params['amount_priceset_level_select']);
784 }
785 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
786 $totalPrice += $lineItem[$optionValueId]['line_total'];
787 if (
788 $component &&
789 isset($lineItem[$optionValueId]['auto_renew']) &&
790 is_numeric($lineItem[$optionValueId]['auto_renew'])
791 ) {
792 $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
793 }
794 break;
795
796 case 'CheckBox':
797 $params['amount_priceset_level_checkbox'] = $optionIds = array();
798 foreach ($params["price_{$id}"] as $optionId => $option) {
799 $optionIds[] = $optionId;
800 $optionLabel = $field['options'][$optionId]['label'];
801 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
802 if (isset($checkboxLevel)) {
803 $checkboxLevel = array_unique(array_merge(
804 $checkboxLevel,
805 array_keys($params['amount_priceset_level_checkbox'])
806 )
807 );
808 }
809 else {
810 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
811 }
812 }
813 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
814 foreach ($optionIds as $optionId) {
815 $totalPrice += $lineItem[$optionId]['line_total'];
816 if (
817 $component &&
818 isset($lineItem[$optionId]['auto_renew']) &&
819 is_numeric($lineItem[$optionId]['auto_renew'])
820 ) {
821 $autoRenew[$lineItem[$optionId]['auto_renew']] += $lineItem[$optionId]['line_total'];
822 }
823 }
824 break;
825 }
826 }
827
828 $amount_level = array();
829 $totalParticipant = 0;
830 if (is_array($lineItem)) {
831 foreach ($lineItem as $values) {
832 $totalParticipant += $values['participant_count'];
833 if ($values['html_type'] == 'Text') {
834 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
835 continue;
836 }
837 $amount_level[] = $values['label'];
838 }
839 }
840
841 $displayParticipantCount = '';
842 if ($totalParticipant > 0) {
843 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
844 }
845 $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
846 $params['amount'] = $totalPrice;
847 if ($component) {
848 foreach ($autoRenew as $dontCare => $eachAmount) {
849 if (!$eachAmount) {
850 unset($autoRenew[$dontCare]);
851 }
852 }
853 if (count($autoRenew) > 1 ) {
854 $params['autoRenew'] = $autoRenew;
855 }
856 }
857 }
858
859 /**
860 * Function to build the price set form.
861 *
862 * @param CRM_Core_Form $form
863 *
864 * @return void
865 * @access public
866 */
867 static function buildPriceSet(&$form) {
868 $priceSetId = $form->get('priceSetId');
869 $userid = $form->getVar('_userID');
870 if (!$priceSetId) {
871 return;
872 }
873
874 $validFieldsOnly = TRUE;
875 $className = CRM_Utils_System::getClassName($form);
876 if (in_array($className, array(
877 'CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'))) {
878 $validFieldsOnly = FALSE;
879 }
880
881 $priceSet = self::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
882 $form->_priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
883 $validPriceFieldIds = array_keys($form->_priceSet['fields']);
884 $form->_quickConfig = $quickConfig = 0;
885 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
886 $quickConfig = 1;
887 }
888
889 $form->assign('quickConfig', $quickConfig);
890 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
891 $form->_quickConfig = $quickConfig;
892 }
893 $form->assign('priceSet', $form->_priceSet);
894
895 $component = 'contribution';
896 if ($className == 'CRM_Member_Form_Membership') {
897 $component = 'membership';
898 }
899
900 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
901 $feeBlock = &$form->_values['fee'];
902 if (!empty($form->_useForMember)) {
903 $component = 'membership';
904 }
905 }
906 else {
907 $feeBlock = &$form->_priceSet['fields'];
908 }
909
910 // call the hook.
911 CRM_Utils_Hook::buildAmount($component, $form, $feeBlock);
912
913 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
914 $adminFieldVisible = false;
915 if (CRM_Core_Permission::check('administer CiviCRM')) {
916 $adminFieldVisible = true;
917 }
918
919 foreach ($feeBlock as $id => $field) {
920 if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
921 (CRM_Utils_Array::value('visibility', $field) == 'admin' && $adminFieldVisible == true) ||
922 !$validFieldsOnly
923 ) {
924 $options = CRM_Utils_Array::value('options', $field);
925 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
926 $checklifetime = self::checkCurrentMembership($options, $userid);
927 if ($checklifetime) {
928 $form->assign('ispricelifetime', TRUE);
929 }
930 }
931 if (!is_array($options) || !in_array($id, $validPriceFieldIds)) {
932 continue;
933 }
934 CRM_Price_BAO_PriceField::addQuickFormElement($form,
935 'price_' . $field['id'],
936 $field['id'],
937 FALSE,
938 CRM_Utils_Array::value('is_required', $field, FALSE),
939 NULL,
940 $options
941 );
942 }
943 }
944 }
945
946 /**
947 * Function to check the current Membership
948 * having end date null.
949 */
950 static function checkCurrentMembership(&$options, $userid) {
951 if (!$userid || empty($options)) {
952 return;
953 }
954 static $_contact_memberships = array();
955 $checklifetime = FALSE;
956 foreach ($options as $key => $value) {
957 if (!empty($value['membership_type_id'])) {
958 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
959 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership::getContactMembership($userid, $value['membership_type_id'], FALSE);
960 }
961 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
962 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
963 unset($options[$key]);
964 $checklifetime = TRUE;
965 }
966 }
967 }
968 if ($checklifetime) {
969 return TRUE;
970 }
971 else {
972 return FALSE;
973 }
974 }
975
976 /**
977 * Function to set daefult the price set fields.
978 *
979 * @param $form
980 * @param $defaults
981 *
982 * @return array $defaults
983 * @access public
984 */
985 static function setDefaultPriceSet(&$form, &$defaults) {
986 if (!isset($form->_priceSet) || empty($form->_priceSet['fields'])) {
987 return $defaults;
988 }
989
990 foreach ($form->_priceSet['fields'] as $key => $val) {
991 foreach ($val['options'] as $keys => $values) {
992 if ($values['is_default']) {
993 if ($val['html_type'] == 'CheckBox') {
994 $defaults["price_{$key}"][$keys] = 1;
995 }
996 else {
997 $defaults["price_{$key}"] = $keys;
998 }
999 }
1000 }
1001 }
1002 return $defaults;
1003 }
1004
1005 /**
1006 * Supports event create function by setting up required price sets, not tested but expect
1007 * it will work for contribution page
1008 * @param array $params as passed to api/bao create fn
1009 * @param CRM_Core_DAO $entity object for given entity
1010 * @param string $entityName name of entity - e.g event
1011 */
1012 static function setPriceSets(&$params, $entity, $entityName) {
1013 if(empty($params['price_set_id']) || !is_array($params['price_set_id'])) {
1014 return;
1015 }
1016 // CRM-14069 note that we may as well start by assuming more than one.
1017 // currently the form does not pass in as an array & will be skipped
1018 // test is passing in as an array but I feel the api should have a metadata that allows
1019 // transform of single to array - seems good for managing transitions - in which case all api
1020 // calls that set price_set_id will hit this
1021 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1022 // all separated values, strings, json half-separated values (in participant we hit this)
1023 // to be converted to json @ api layer
1024 $pse = new CRM_Price_DAO_PriceSetEntity();
1025 $pse->entity_table = 'civicrm_' . $entityName;
1026 $pse->entity_id = $entity->id;
1027 while ($pse->fetch()) {
1028 if(!in_array($pse->price_set_id, $params['price_set_id'])) {
1029 // note an even more aggressive form of this deletion currently happens in event form
1030 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1031 // on the participant record
1032 if (CRM_Price_BAO_PriceSet::removeFrom('civicrm_' . $entityName, $entity->id)) {
1033 CRM_Core_BAO_Discount::del($this->_id,'civicrm_' . $entityName);
1034 }
1035 }
1036 }
1037 foreach ($params['price_set_id'] as $priceSetID) {
1038 CRM_Price_BAO_PriceSet::addTo('civicrm_' . $entityName, $entity->id, $priceSetID);
1039 //@todo - how should we do this - copied from form
1040 //if (CRM_Utils_Array::value('price_field_id', $params)) {
1041 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1042 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1043 //}
1044 }
1045 }
1046 /**
1047 * Get field ids of a price set
1048 *
1049 * @param int $id Price Set id
1050 *
1051 * @return array of the field ids
1052 *
1053 * @access public
1054 * @static
1055 */
1056 public static function getFieldIds($id) {
1057 $priceField = new CRM_Price_DAO_PriceField();
1058 $priceField->price_set_id = $id;
1059 $priceField->find();
1060 while ($priceField->fetch()) {
1061 $var[] = $priceField->id;
1062 }
1063 return $var;
1064 }
1065
1066 /**
1067 * This function is to make a copy of a price set, including
1068 * all the fields
1069 *
1070 * @param int $id the price set id to copy
1071 *
1072 * @return the copy object
1073 * @access public
1074 * @static
1075 */
1076 static function copy($id) {
1077 $maxId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1078
1079 $title = ts('[Copy id %1]', array(1 => $maxId + 1));
1080 $fieldsFix = array(
1081 'suffix' => array('title' => ' ' . $title,
1082 'name' => '__Copy_id_' . ($maxId + 1) . '_',
1083 ),
1084 );
1085
1086 $copy = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSet',
1087 array('id' => $id),
1088 NULL,
1089 $fieldsFix
1090 );
1091
1092 //copying all the blocks pertaining to the price set
1093 $copyPriceField = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceField',
1094 array('price_set_id' => $id),
1095 array('price_set_id' => $copy->id)
1096 );
1097 if (!empty($copyPriceField)) {
1098 $price = array_combine(self::getFieldIds($id), self::getFieldIds($copy->id));
1099
1100 //copy option group and values
1101 foreach ($price as $originalId => $copyId) {
1102 CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1103 array('price_field_id' => $originalId),
1104 array('price_field_id' => $copyId)
1105 );
1106 }
1107 }
1108 $copy->save();
1109
1110 CRM_Utils_Hook::copy('Set', $copy);
1111 return $copy;
1112 }
1113
1114 /**
1115 * This function is to check price set permission
1116 *
1117 * @param int $sid the price set id
1118 *
1119 * @return bool
1120 */
1121 static function checkPermission($sid) {
1122 if ($sid && self::eventPriceSetDomainID()) {
1123 $domain_id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1124 if (CRM_Core_Config::domainID() != $domain_id) {
1125 CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
1126 }
1127 }
1128 return TRUE;
1129 }
1130
1131 /**
1132 * Get the sum of participant count
1133 * for all fields of given price set.
1134 *
1135 * @param int $sid the price set id
1136 *
1137 * @param bool $onlyActive
1138 *
1139 * @return int|null|string
1140 * @access public
1141 * @static
1142 */
1143 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1144 $count = 0;
1145 if (!$sid) {
1146 return $count;
1147 }
1148
1149 $where = NULL;
1150 if ($onlyActive) {
1151 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1152 }
1153
1154 static $pricesetFieldCount = array();
1155 if (!isset($pricesetFieldCount[$sid])) {
1156 $sql = "
1157 SELECT sum(value.count) as totalCount
1158 FROM civicrm_price_field_value value
1159 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1160 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1161 WHERE pset.id = %1
1162 $where";
1163
1164 $count = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1165 $pricesetFieldCount[$sid] = ($count) ? $count : 0;
1166 }
1167
1168 return $pricesetFieldCount[$sid];
1169 }
1170
1171 /**
1172 * @param $ids
1173 *
1174 * @return array
1175 */
1176 public static function getMembershipCount($ids) {
1177 $queryString = "
1178 SELECT count( pfv.id ) AS count, pfv.id AS id
1179 FROM civicrm_price_field_value pfv
1180 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1181 WHERE pfv.id IN ( $ids )
1182 GROUP BY mt.member_of_contact_id";
1183
1184 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
1185 $count = array();
1186
1187 while ($crmDAO->fetch()) {
1188 $count[$crmDAO->id] = $crmDAO->count;
1189 }
1190
1191 return $count;
1192 }
1193
1194 /**
1195 * Function to check if auto renew option should be shown
1196 *
1197 * @param int $priceSetId price set id
1198 *
1199 * @return int $autoRenewOption ( 0:hide, 1:optional 2:required )
1200 */
1201 public static function checkAutoRenewForPriceSet($priceSetId) {
1202 // auto-renew option should be visible if membership types associated with all the fields has
1203 // been set for auto-renew option
1204 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1205
1206 // get the membership type auto renew option and check if required or optional
1207 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1208 FROM civicrm_price_field_value pfv
1209 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1210 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1211 WHERE pf.price_set_id = %1
1212 AND pf.is_active = 1
1213 AND pfv.is_active = 1';
1214
1215 $params = array(1 => array($priceSetId, 'Integer'));
1216
1217 $dao = CRM_Core_DAO::executeQuery($query, $params);
1218 $autoRenewOption = 2;
1219 $interval = $unit = array();
1220 while ($dao->fetch()) {
1221 if (!$dao->auto_renew) {
1222 $autoRenewOption = 0;
1223 break;
1224 }
1225 if ($dao->auto_renew == 1) {
1226 $autoRenewOption = 1;
1227 }
1228
1229 $interval[$dao->duration_interval] = $dao->duration_interval;
1230 $unit[$dao->duration_unit] = $dao->duration_unit;
1231 }
1232
1233 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1234 return $autoRenewOption;
1235 }
1236 else {
1237 return 0;
1238 }
1239 }
1240
1241 /**
1242 * Function to retrieve auto renew frequency and interval
1243 *
1244 * @param int $priceSetId price set id
1245 *
1246 * @return array associate array of frequency interval and unit
1247 * @static
1248 * @access public
1249 */
1250 public static function getRecurDetails($priceSetId) {
1251 $query = 'SELECT mt.duration_interval, mt.duration_unit
1252 FROM civicrm_price_field_value pfv
1253 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1254 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1255 WHERE pf.price_set_id = %1 LIMIT 1';
1256
1257 $params = array(1 => array($priceSetId, 'Integer'));
1258 $dao = CRM_Core_DAO::executeQuery($query, $params);
1259 $dao->fetch();
1260 return array($dao->duration_interval, $dao->duration_unit);
1261 }
1262
1263 /**
1264 * @return object
1265 */
1266 static function eventPriceSetDomainID() {
1267 return CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME,
1268 'event_price_set_domain_id',
1269 NULL, FALSE
1270 );
1271 }
1272
1273 /**
1274 * update the is_quick_config flag in the db
1275 *
1276 * @param int $id id of the database record
1277 * @param boolean $isQuickConfig value we want to set the is_quick_config field
1278 *
1279 * @return Object DAO object on sucess, null otherwise
1280 * @static
1281 * @access public
1282 */
1283 static function setIsQuickConfig($id, $isQuickConfig) {
1284 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1285 }
1286
1287 /**
1288 * Check if price set id provides option for
1289 * user to select both auto-renew and non-auto-renew memberships
1290 *
1291 * @access public
1292 * @static
1293 *
1294 */
1295 public static function checkMembershipPriceSet($id) {
1296 $query =
1297 "
1298 SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1299 FROM civicrm_price_field_value pfv
1300 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1301 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1302 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1303 WHERE ps.id = %1
1304 ";
1305
1306 $params = array(1 => array($id, 'Integer'));
1307 $dao = CRM_Core_DAO::executeQuery($query, $params);
1308
1309 $autoRenew = array();
1310 //FIXME: do a comprehensive check of whether
1311 //2 membership types can be selected
1312 //instead of comparing all of them
1313 while ($dao->fetch()) {
1314 //temp fix for #CRM-10370
1315 //if its NULL consider it '0' i.e. 'No auto-renew option'
1316 $daoAutoRenew = $dao->auto_renew;
1317 if ($daoAutoRenew === NULL) {
1318 $daoAutoRenew = 0;
1319 }
1320 if (!empty($autoRenew) && !in_array($daoAutoRenew, $autoRenew)) {
1321 return true;
1322 }
1323 $autoRenew[] = $daoAutoRenew;
1324 }
1325 return false;
1326 }
1327
1328 /**
1329 * Copy priceSet when event/contibution page is copied
1330 *
1331 * @params string $baoName BAO name
1332 * @params int $id old event/contribution page id
1333 * @params int $newId newly created event/contribution page id
1334 *
1335 * @param string $baoName
1336 * @param integer $id
1337 * @param integer $newId
1338 */
1339 static function copyPriceSet($baoName, $id, $newId) {
1340 $priceSetId = CRM_Price_BAO_PriceSet::getFor($baoName, $id);
1341 if ($priceSetId) {
1342 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1343 if($isQuickConfig) {
1344 $copyPriceSet = &CRM_Price_BAO_PriceSet::copy($priceSetId);
1345 CRM_Price_BAO_PriceSet::addTo($baoName, $newId, $copyPriceSet->id);
1346 }
1347 else {
1348 $copyPriceSet = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1349 array(
1350 'entity_id' => $id,
1351 'entity_table' => $baoName,
1352 ),
1353 array('entity_id' => $newId)
1354 );
1355 }
1356 // copy event discount
1357 if ($baoName == 'civicrm_event') {
1358 $discount = CRM_Core_BAO_Discount::getOptionGroup($id, 'civicrm_event');
1359 foreach ($discount as $discountId => $setId) {
1360
1361 $copyPriceSet = &CRM_Price_BAO_PriceSet::copy($setId);
1362
1363 CRM_Core_DAO::copyGeneric(
1364 'CRM_Core_DAO_Discount',
1365 array(
1366 'id' => $discountId,
1367 ),
1368 array(
1369 'entity_id' => $newId,
1370 'price_set_id' => $copyPriceSet->id,
1371 )
1372 );
1373 }
1374 }
1375 }
1376 }
1377 }
1378