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