Merge remote branch 'canonical/master' into merge-20140930
[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 = $totalTax = 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 if (CRM_Utils_Array::value('tax_rate', $field['options'][key($field['options'])])) {
740 $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
741 $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
742 }
743 if (CRM_Utils_Array::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
744 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
745 if (array_key_exists($params['financial_type_id'], $taxRates)) {
746 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
747 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
748 $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
749 $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
750 $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
751 }
752 }
753 $totalPrice += $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[key($field['options'])]);
754 break;
755
756 case 'Radio':
757 //special case if user select -none-
758 if ($params["price_{$id}"] <= 0) {
759 continue;
760 }
761 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
762 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
763 $optionLabel = CRM_Utils_Array::value('label', $field['options'][$optionValueId]);
764 $params['amount_priceset_level_radio'] = array();
765 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
766 if (isset($radioLevel)) {
767 $radioLevel = array_merge($radioLevel,
768 array_keys($params['amount_priceset_level_radio'])
769 );
770 }
771 else {
772 $radioLevel = array_keys($params['amount_priceset_level_radio']);
773 }
774 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
775 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
776 $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
777 $totalTax += $field['options'][$optionValueId]['tax_amount'];
778 if (CRM_Utils_Array::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
779 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
780 }
781 }
782 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
783 if (
784 $component &&
785 // auto_renew exists and is empty in some workflows, which php treat as a 0
786 // and hence we explicitly check to see if auto_renew is numeric
787 isset($lineItem[$optionValueId]['auto_renew']) &&
788 is_numeric($lineItem[$optionValueId]['auto_renew'])
789 ) {
790 $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
791 }
792 break;
793
794 case 'Select':
795 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
796 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
797 $optionLabel = $field['options'][$optionValueId]['label'];
798 $params['amount_priceset_level_select'] = array();
799 $params['amount_priceset_level_select'][CRM_Utils_Array::key(1, $params["price_{$id}"])] = $optionLabel;
800 if (isset($selectLevel)) {
801 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
802 }
803 else {
804 $selectLevel = array_keys($params['amount_priceset_level_select']);
805 }
806 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
807 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
808 $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
809 $totalTax += $field['options'][$optionValueId]['tax_amount'];
810 }
811 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
812 if (
813 $component &&
814 isset($lineItem[$optionValueId]['auto_renew']) &&
815 is_numeric($lineItem[$optionValueId]['auto_renew'])
816 ) {
817 $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
818 }
819 break;
820
821 case 'CheckBox':
822 $params['amount_priceset_level_checkbox'] = $optionIds = array();
823 foreach ($params["price_{$id}"] as $optionId => $option) {
824 $optionIds[] = $optionId;
825 $optionLabel = $field['options'][$optionId]['label'];
826 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
827 if (isset($checkboxLevel)) {
828 $checkboxLevel = array_unique(array_merge(
829 $checkboxLevel,
830 array_keys($params['amount_priceset_level_checkbox'])
831 )
832 );
833 }
834 else {
835 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
836 }
837 }
838 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
839 foreach ($optionIds as $optionId) {
840 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionId])) {
841 $lineItem = self::setLineItem($field, $lineItem, $optionId);
842 $totalTax += $field['options'][$optionId]['tax_amount'];
843 }
844 $totalPrice += $lineItem[$optionId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionId]);
845 if (
846 $component &&
847 isset($lineItem[$optionId]['auto_renew']) &&
848 is_numeric($lineItem[$optionId]['auto_renew'])
849 ) {
850 $autoRenew[$lineItem[$optionId]['auto_renew']] += $lineItem[$optionId]['line_total'];
851 }
852 }
853 break;
854 }
855 }
856
857 $amount_level = array();
858 $totalParticipant = 0;
859 if (is_array($lineItem)) {
860 foreach ($lineItem as $values) {
861 $totalParticipant += $values['participant_count'];
862 if ($values['html_type'] == 'Text') {
863 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
864 continue;
865 }
866 $amount_level[] = $values['label'];
867 }
868 }
869
870 $displayParticipantCount = '';
871 if ($totalParticipant > 0) {
872 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
873 }
874 $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
875 $params['amount'] = $totalPrice;
876 $params['tax_amount'] = $totalTax;
877 if ($component) {
878 foreach ($autoRenew as $dontCare => $eachAmount) {
879 if (!$eachAmount) {
880 unset($autoRenew[$dontCare]);
881 }
882 }
883 if (count($autoRenew) > 1 ) {
884 $params['autoRenew'] = $autoRenew;
885 }
886 }
887 }
888
889 /**
890 * Function to build the price set form.
891 *
892 * @param CRM_Core_Form $form
893 *
894 * @return void
895 * @access public
896 */
897 static function buildPriceSet(&$form) {
898 $priceSetId = $form->get('priceSetId');
899 $userid = $form->getVar('_userID');
900 if (!$priceSetId) {
901 return;
902 }
903
904 $validFieldsOnly = TRUE;
905 $className = CRM_Utils_System::getClassName($form);
906 if (in_array($className, array(
907 'CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'))) {
908 $validFieldsOnly = FALSE;
909 }
910
911 $priceSet = self::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
912 $form->_priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
913 $validPriceFieldIds = array_keys($form->_priceSet['fields']);
914 $form->_quickConfig = $quickConfig = 0;
915 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
916 $quickConfig = 1;
917 }
918
919 $form->assign('quickConfig', $quickConfig);
920 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
921 $form->_quickConfig = $quickConfig;
922 }
923 $form->assign('priceSet', $form->_priceSet);
924
925 $component = 'contribution';
926 if ($className == 'CRM_Member_Form_Membership') {
927 $component = 'membership';
928 }
929
930 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
931 $feeBlock = &$form->_values['fee'];
932 if (!empty($form->_useForMember)) {
933 $component = 'membership';
934 }
935 }
936 else {
937 $feeBlock = &$form->_priceSet['fields'];
938 }
939
940 // call the hook.
941 CRM_Utils_Hook::buildAmount($component, $form, $feeBlock);
942
943 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
944 $adminFieldVisible = false;
945 if (CRM_Core_Permission::check('administer CiviCRM')) {
946 $adminFieldVisible = true;
947 }
948
949 foreach ($feeBlock as $id => $field) {
950 if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
951 (CRM_Utils_Array::value('visibility', $field) == 'admin' && $adminFieldVisible == true) ||
952 !$validFieldsOnly
953 ) {
954 $options = CRM_Utils_Array::value('options', $field);
955 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
956 $checklifetime = self::checkCurrentMembership($options, $userid);
957 if ($checklifetime) {
958 $form->assign('ispricelifetime', TRUE);
959 }
960 }
961 if (!is_array($options) || !in_array($id, $validPriceFieldIds)) {
962 continue;
963 }
964 CRM_Price_BAO_PriceField::addQuickFormElement($form,
965 'price_' . $field['id'],
966 $field['id'],
967 FALSE,
968 CRM_Utils_Array::value('is_required', $field, FALSE),
969 NULL,
970 $options
971 );
972 }
973 }
974 }
975
976 /**
977 * Function to check the current Membership
978 * having end date null.
979 */
980 static function checkCurrentMembership(&$options, $userid) {
981 if (!$userid || empty($options)) {
982 return;
983 }
984 static $_contact_memberships = array();
985 $checklifetime = FALSE;
986 foreach ($options as $key => $value) {
987 if (!empty($value['membership_type_id'])) {
988 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
989 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership::getContactMembership($userid, $value['membership_type_id'], FALSE);
990 }
991 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
992 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
993 unset($options[$key]);
994 $checklifetime = TRUE;
995 }
996 }
997 }
998 if ($checklifetime) {
999 return TRUE;
1000 }
1001 else {
1002 return FALSE;
1003 }
1004 }
1005
1006 /**
1007 * Function to set daefult the price set fields.
1008 *
1009 * @param $form
1010 * @param $defaults
1011 *
1012 * @return array $defaults
1013 * @access public
1014 */
1015 static function setDefaultPriceSet(&$form, &$defaults) {
1016 if (!isset($form->_priceSet) || empty($form->_priceSet['fields'])) {
1017 return $defaults;
1018 }
1019
1020 foreach ($form->_priceSet['fields'] as $key => $val) {
1021 foreach ($val['options'] as $keys => $values) {
1022 if ($values['is_default']) {
1023 if ($val['html_type'] == 'CheckBox') {
1024 $defaults["price_{$key}"][$keys] = 1;
1025 }
1026 else {
1027 $defaults["price_{$key}"] = $keys;
1028 }
1029 }
1030 }
1031 }
1032 return $defaults;
1033 }
1034
1035 /**
1036 * Supports event create function by setting up required price sets, not tested but expect
1037 * it will work for contribution page
1038 * @param array $params as passed to api/bao create fn
1039 * @param CRM_Core_DAO $entity object for given entity
1040 * @param string $entityName name of entity - e.g event
1041 */
1042 static function setPriceSets(&$params, $entity, $entityName) {
1043 if(empty($params['price_set_id']) || !is_array($params['price_set_id'])) {
1044 return;
1045 }
1046 // CRM-14069 note that we may as well start by assuming more than one.
1047 // currently the form does not pass in as an array & will be skipped
1048 // test is passing in as an array but I feel the api should have a metadata that allows
1049 // transform of single to array - seems good for managing transitions - in which case all api
1050 // calls that set price_set_id will hit this
1051 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1052 // all separated values, strings, json half-separated values (in participant we hit this)
1053 // to be converted to json @ api layer
1054 $pse = new CRM_Price_DAO_PriceSetEntity();
1055 $pse->entity_table = 'civicrm_' . $entityName;
1056 $pse->entity_id = $entity->id;
1057 while ($pse->fetch()) {
1058 if(!in_array($pse->price_set_id, $params['price_set_id'])) {
1059 // note an even more aggressive form of this deletion currently happens in event form
1060 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1061 // on the participant record
1062 if (CRM_Price_BAO_PriceSet::removeFrom('civicrm_' . $entityName, $entity->id)) {
1063 CRM_Core_BAO_Discount::del($this->_id,'civicrm_' . $entityName);
1064 }
1065 }
1066 }
1067 foreach ($params['price_set_id'] as $priceSetID) {
1068 CRM_Price_BAO_PriceSet::addTo('civicrm_' . $entityName, $entity->id, $priceSetID);
1069 //@todo - how should we do this - copied from form
1070 //if (CRM_Utils_Array::value('price_field_id', $params)) {
1071 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1072 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1073 //}
1074 }
1075 }
1076 /**
1077 * Get field ids of a price set
1078 *
1079 * @param int $id Price Set id
1080 *
1081 * @return array of the field ids
1082 *
1083 * @access public
1084 * @static
1085 */
1086 public static function getFieldIds($id) {
1087 $priceField = new CRM_Price_DAO_PriceField();
1088 $priceField->price_set_id = $id;
1089 $priceField->find();
1090 while ($priceField->fetch()) {
1091 $var[] = $priceField->id;
1092 }
1093 return $var;
1094 }
1095
1096 /**
1097 * This function is to make a copy of a price set, including
1098 * all the fields
1099 *
1100 * @param int $id the price set id to copy
1101 *
1102 * @return the copy object
1103 * @access public
1104 * @static
1105 */
1106 static function copy($id) {
1107 $maxId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1108
1109 $title = ts('[Copy id %1]', array(1 => $maxId + 1));
1110 $fieldsFix = array(
1111 'suffix' => array('title' => ' ' . $title,
1112 'name' => '__Copy_id_' . ($maxId + 1) . '_',
1113 ),
1114 );
1115
1116 $copy = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSet',
1117 array('id' => $id),
1118 NULL,
1119 $fieldsFix
1120 );
1121
1122 //copying all the blocks pertaining to the price set
1123 $copyPriceField = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceField',
1124 array('price_set_id' => $id),
1125 array('price_set_id' => $copy->id)
1126 );
1127 if (!empty($copyPriceField)) {
1128 $price = array_combine(self::getFieldIds($id), self::getFieldIds($copy->id));
1129
1130 //copy option group and values
1131 foreach ($price as $originalId => $copyId) {
1132 CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1133 array('price_field_id' => $originalId),
1134 array('price_field_id' => $copyId)
1135 );
1136 }
1137 }
1138 $copy->save();
1139
1140 CRM_Utils_Hook::copy('Set', $copy);
1141 return $copy;
1142 }
1143
1144 /**
1145 * This function is to check price set permission
1146 *
1147 * @param int $sid the price set id
1148 *
1149 * @return bool
1150 */
1151 static function checkPermission($sid) {
1152 if ($sid && self::eventPriceSetDomainID()) {
1153 $domain_id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1154 if (CRM_Core_Config::domainID() != $domain_id) {
1155 CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
1156 }
1157 }
1158 return TRUE;
1159 }
1160
1161 /**
1162 * Get the sum of participant count
1163 * for all fields of given price set.
1164 *
1165 * @param int $sid the price set id
1166 *
1167 * @param bool $onlyActive
1168 *
1169 * @return int|null|string
1170 * @access public
1171 * @static
1172 */
1173 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1174 $count = 0;
1175 if (!$sid) {
1176 return $count;
1177 }
1178
1179 $where = NULL;
1180 if ($onlyActive) {
1181 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1182 }
1183
1184 static $pricesetFieldCount = array();
1185 if (!isset($pricesetFieldCount[$sid])) {
1186 $sql = "
1187 SELECT sum(value.count) as totalCount
1188 FROM civicrm_price_field_value value
1189 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1190 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1191 WHERE pset.id = %1
1192 $where";
1193
1194 $count = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1195 $pricesetFieldCount[$sid] = ($count) ? $count : 0;
1196 }
1197
1198 return $pricesetFieldCount[$sid];
1199 }
1200
1201 /**
1202 * @param $ids
1203 *
1204 * @return array
1205 */
1206 public static function getMembershipCount($ids) {
1207 $queryString = "
1208 SELECT count( pfv.id ) AS count, pfv.id AS id
1209 FROM civicrm_price_field_value pfv
1210 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1211 WHERE pfv.id IN ( $ids )
1212 GROUP BY mt.member_of_contact_id";
1213
1214 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
1215 $count = array();
1216
1217 while ($crmDAO->fetch()) {
1218 $count[$crmDAO->id] = $crmDAO->count;
1219 }
1220
1221 return $count;
1222 }
1223
1224 /**
1225 * Function to check if auto renew option should be shown
1226 *
1227 * @param int $priceSetId price set id
1228 *
1229 * @return int $autoRenewOption ( 0:hide, 1:optional 2:required )
1230 */
1231 public static function checkAutoRenewForPriceSet($priceSetId) {
1232 // auto-renew option should be visible if membership types associated with all the fields has
1233 // been set for auto-renew option
1234 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1235
1236 // get the membership type auto renew option and check if required or optional
1237 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1238 FROM civicrm_price_field_value pfv
1239 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1240 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1241 WHERE pf.price_set_id = %1
1242 AND pf.is_active = 1
1243 AND pfv.is_active = 1';
1244
1245 $params = array(1 => array($priceSetId, 'Integer'));
1246
1247 $dao = CRM_Core_DAO::executeQuery($query, $params);
1248 $autoRenewOption = 2;
1249 $interval = $unit = array();
1250 while ($dao->fetch()) {
1251 if (!$dao->auto_renew) {
1252 $autoRenewOption = 0;
1253 break;
1254 }
1255 if ($dao->auto_renew == 1) {
1256 $autoRenewOption = 1;
1257 }
1258
1259 $interval[$dao->duration_interval] = $dao->duration_interval;
1260 $unit[$dao->duration_unit] = $dao->duration_unit;
1261 }
1262
1263 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1264 return $autoRenewOption;
1265 }
1266 else {
1267 return 0;
1268 }
1269 }
1270
1271 /**
1272 * Function to retrieve auto renew frequency and interval
1273 *
1274 * @param int $priceSetId price set id
1275 *
1276 * @return array associate array of frequency interval and unit
1277 * @static
1278 * @access public
1279 */
1280 public static function getRecurDetails($priceSetId) {
1281 $query = 'SELECT mt.duration_interval, mt.duration_unit
1282 FROM civicrm_price_field_value pfv
1283 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1284 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1285 WHERE pf.price_set_id = %1 LIMIT 1';
1286
1287 $params = array(1 => array($priceSetId, 'Integer'));
1288 $dao = CRM_Core_DAO::executeQuery($query, $params);
1289 $dao->fetch();
1290 return array($dao->duration_interval, $dao->duration_unit);
1291 }
1292
1293 /**
1294 * @return object
1295 */
1296 static function eventPriceSetDomainID() {
1297 return CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME,
1298 'event_price_set_domain_id',
1299 NULL, FALSE
1300 );
1301 }
1302
1303 /**
1304 * update the is_quick_config flag in the db
1305 *
1306 * @param int $id id of the database record
1307 * @param boolean $isQuickConfig value we want to set the is_quick_config field
1308 *
1309 * @return Object DAO object on sucess, null otherwise
1310 * @static
1311 * @access public
1312 */
1313 static function setIsQuickConfig($id, $isQuickConfig) {
1314 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1315 }
1316
1317 /**
1318 * Check if price set id provides option for
1319 * user to select both auto-renew and non-auto-renew memberships
1320 *
1321 * @access public
1322 * @static
1323 *
1324 */
1325 public static function checkMembershipPriceSet($id) {
1326 $query =
1327 "
1328 SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1329 FROM civicrm_price_field_value pfv
1330 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1331 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1332 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1333 WHERE ps.id = %1
1334 ";
1335
1336 $params = array(1 => array($id, 'Integer'));
1337 $dao = CRM_Core_DAO::executeQuery($query, $params);
1338
1339 $autoRenew = array();
1340 //FIXME: do a comprehensive check of whether
1341 //2 membership types can be selected
1342 //instead of comparing all of them
1343 while ($dao->fetch()) {
1344 //temp fix for #CRM-10370
1345 //if its NULL consider it '0' i.e. 'No auto-renew option'
1346 $daoAutoRenew = $dao->auto_renew;
1347 if ($daoAutoRenew === NULL) {
1348 $daoAutoRenew = 0;
1349 }
1350 if (!empty($autoRenew) && !in_array($daoAutoRenew, $autoRenew)) {
1351 return true;
1352 }
1353 $autoRenew[] = $daoAutoRenew;
1354 }
1355 return false;
1356 }
1357
1358 /**
1359 * Copy priceSet when event/contibution page is copied
1360 *
1361 * @params string $baoName BAO name
1362 * @params int $id old event/contribution page id
1363 * @params int $newId newly created event/contribution page id
1364 *
1365 * @param string $baoName
1366 * @param integer $id
1367 * @param integer $newId
1368 */
1369 static function copyPriceSet($baoName, $id, $newId) {
1370 $priceSetId = CRM_Price_BAO_PriceSet::getFor($baoName, $id);
1371 if ($priceSetId) {
1372 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1373 if($isQuickConfig) {
1374 $copyPriceSet = &CRM_Price_BAO_PriceSet::copy($priceSetId);
1375 CRM_Price_BAO_PriceSet::addTo($baoName, $newId, $copyPriceSet->id);
1376 }
1377 else {
1378 $copyPriceSet = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1379 array(
1380 'entity_id' => $id,
1381 'entity_table' => $baoName,
1382 ),
1383 array('entity_id' => $newId)
1384 );
1385 }
1386 // copy event discount
1387 if ($baoName == 'civicrm_event') {
1388 $discount = CRM_Core_BAO_Discount::getOptionGroup($id, 'civicrm_event');
1389 foreach ($discount as $discountId => $setId) {
1390
1391 $copyPriceSet = &CRM_Price_BAO_PriceSet::copy($setId);
1392
1393 CRM_Core_DAO::copyGeneric(
1394 'CRM_Core_DAO_Discount',
1395 array(
1396 'id' => $discountId,
1397 ),
1398 array(
1399 'entity_id' => $newId,
1400 'price_set_id' => $copyPriceSet->id,
1401 )
1402 );
1403 }
1404 }
1405 }
1406 }
1407
1408 /*
1409 * Function to set tax_amount and tax_rate in LineItem
1410 *
1411 *
1412 */
1413 static function setLineItem($field, $lineItem, $optionValueId) {
1414 if ($field['html_type'] == 'Text') {
1415 $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
1416 }
1417 else {
1418 $taxAmount = $field['options'][$optionValueId]['tax_amount'];
1419 }
1420 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1421 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1422 $lineItem[$optionValueId]['tax_rate'] = $taxRate;
1423
1424 return $lineItem;
1425 }
1426 }
1427