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