INFRA-132 - Standardize integer to int
[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
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
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 int|false
379 * price_set_id, or false if none found
380 */
381 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
382 if (!$entityTable || !$entityId) {
383 return FALSE;
384 }
385
386 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
387 FROM civicrm_price_set ps
388 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
389 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
390 if ($isQuickConfig) {
391 $sql .= ' AND ps.is_quick_config = 0 ';
392 }
393 $params = array(
394 1 => array($entityTable, 'String'),
395 2 => array($entityId, 'Integer'),
396 );
397 if ($usedFor) {
398 $sql .= " AND ps.extends LIKE '%%3%' ";
399 $params[3] = array($usedFor, 'Integer');
400 }
401
402 $dao = CRM_Core_DAO::executeQuery($sql, $params);
403 $dao->fetch();
404 $setName = (isset($dao->price_set_name)) ? $dao->price_set_name : FALSE;
405 return (isset($dao->price_set_id)) ? $dao->price_set_id : FALSE;
406 }
407
408 /**
409 * Find a price_set_id associated with the given option value or field ID
410 *
411 * @param array $params
412 * (reference) an assoc array of name/value pairs.
413 * array may contain either option id or
414 * price field id
415 *
416 * @return int|NULL
417 * 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',
914 'CRM_Member_Form_Membership'
915 ))) {
916 $validFieldsOnly = FALSE;
917 }
918
919 $priceSet = self::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
920 $form->_priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
921 $validPriceFieldIds = array_keys($form->_priceSet['fields']);
922 $form->_quickConfig = $quickConfig = 0;
923 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
924 $quickConfig = 1;
925 }
926
927 $form->assign('quickConfig', $quickConfig);
928 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
929 $form->_quickConfig = $quickConfig;
930 }
931 $form->assign('priceSet', $form->_priceSet);
932
933 $component = 'contribution';
934 if ($className == 'CRM_Member_Form_Membership') {
935 $component = 'membership';
936 }
937
938 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
939 $feeBlock = &$form->_values['fee'];
940 if (!empty($form->_useForMember)) {
941 $component = 'membership';
942 }
943 }
944 else {
945 $feeBlock = &$form->_priceSet['fields'];
946 }
947
948 // call the hook.
949 CRM_Utils_Hook::buildAmount($component, $form, $feeBlock);
950
951 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
952 $adminFieldVisible = FALSE;
953 if (CRM_Core_Permission::check('administer CiviCRM')) {
954 $adminFieldVisible = TRUE;
955 }
956
957 foreach ($feeBlock as $id => $field) {
958 if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
959 (CRM_Utils_Array::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
960 !$validFieldsOnly
961 ) {
962 $options = CRM_Utils_Array::value('options', $field);
963 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
964 $userid = $form->getVar('_membershipContactID');
965 $checklifetime = self::checkCurrentMembership($options, $userid);
966 if ($checklifetime) {
967 $form->assign('ispricelifetime', TRUE);
968 }
969 }
970 if (!is_array($options) || !in_array($id, $validPriceFieldIds)) {
971 continue;
972 }
973 CRM_Price_BAO_PriceField::addQuickFormElement($form,
974 'price_' . $field['id'],
975 $field['id'],
976 FALSE,
977 CRM_Utils_Array::value('is_required', $field, FALSE),
978 NULL,
979 $options
980 );
981 }
982 }
983 }
984
985 /**
986 * Check the current Membership
987 * having end date null.
988 */
989 public static function checkCurrentMembership(&$options, $userid) {
990 if (!$userid || empty($options)) {
991 return;
992 }
993 static $_contact_memberships = array();
994 $checklifetime = FALSE;
995 foreach ($options as $key => $value) {
996 if (!empty($value['membership_type_id'])) {
997 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
998 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership::getContactMembership($userid, $value['membership_type_id'], FALSE);
999 }
1000 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
1001 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
1002 unset($options[$key]);
1003 $checklifetime = TRUE;
1004 }
1005 }
1006 }
1007 if ($checklifetime) {
1008 return TRUE;
1009 }
1010 else {
1011 return FALSE;
1012 }
1013 }
1014
1015 /**
1016 * Set daefult the price set fields.
1017 *
1018 * @param CRM_Core_Form $form
1019 * @param $defaults
1020 *
1021 * @return array
1022 */
1023 public static function setDefaultPriceSet(&$form, &$defaults) {
1024 if (!isset($form->_priceSet) || empty($form->_priceSet['fields'])) {
1025 return $defaults;
1026 }
1027
1028 foreach ($form->_priceSet['fields'] as $key => $val) {
1029 foreach ($val['options'] as $keys => $values) {
1030 if ($values['is_default']) {
1031 if ($val['html_type'] == 'CheckBox') {
1032 $defaults["price_{$key}"][$keys] = 1;
1033 }
1034 else {
1035 $defaults["price_{$key}"] = $keys;
1036 }
1037 }
1038 }
1039 }
1040 return $defaults;
1041 }
1042
1043 /**
1044 * Supports event create function by setting up required price sets, not tested but expect
1045 * it will work for contribution page
1046 * @param array $params
1047 * As passed to api/bao create fn.
1048 * @param CRM_Core_DAO $entity
1049 * Object for given entity.
1050 * @param string $entityName
1051 * Name of entity - e.g event.
1052 */
1053 public static function setPriceSets(&$params, $entity, $entityName) {
1054 if (empty($params['price_set_id']) || !is_array($params['price_set_id'])) {
1055 return;
1056 }
1057 // CRM-14069 note that we may as well start by assuming more than one.
1058 // currently the form does not pass in as an array & will be skipped
1059 // test is passing in as an array but I feel the api should have a metadata that allows
1060 // transform of single to array - seems good for managing transitions - in which case all api
1061 // calls that set price_set_id will hit this
1062 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1063 // all separated values, strings, json half-separated values (in participant we hit this)
1064 // to be converted to json @ api layer
1065 $pse = new CRM_Price_DAO_PriceSetEntity();
1066 $pse->entity_table = 'civicrm_' . $entityName;
1067 $pse->entity_id = $entity->id;
1068 while ($pse->fetch()) {
1069 if (!in_array($pse->price_set_id, $params['price_set_id'])) {
1070 // note an even more aggressive form of this deletion currently happens in event form
1071 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1072 // on the participant record
1073 if (CRM_Price_BAO_PriceSet::removeFrom('civicrm_' . $entityName, $entity->id)) {
1074 CRM_Core_BAO_Discount::del($entity->id, 'civicrm_' . $entityName);
1075 }
1076 }
1077 }
1078 foreach ($params['price_set_id'] as $priceSetID) {
1079 CRM_Price_BAO_PriceSet::addTo('civicrm_' . $entityName, $entity->id, $priceSetID);
1080 //@todo - how should we do this - copied from form
1081 //if (CRM_Utils_Array::value('price_field_id', $params)) {
1082 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1083 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1084 //}
1085 }
1086 }
1087
1088 /**
1089 * Get field ids of a price set
1090 *
1091 * @param int $id
1092 * Price Set id.
1093 *
1094 * @return array
1095 * Array of the field ids
1096 *
1097 * @static
1098 */
1099 public static function getFieldIds($id) {
1100 $priceField = new CRM_Price_DAO_PriceField();
1101 $priceField->price_set_id = $id;
1102 $priceField->find();
1103 while ($priceField->fetch()) {
1104 $var[] = $priceField->id;
1105 }
1106 return $var;
1107 }
1108
1109 /**
1110 * Copy a price set, including all the fields
1111 *
1112 * @param int $id
1113 * The price set id to copy.
1114 *
1115 * @return CRM_Price_DAO_PriceSet
1116 * @static
1117 */
1118 public static function copy($id) {
1119 $maxId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1120
1121 $title = ts('[Copy id %1]', array(1 => $maxId + 1));
1122 $fieldsFix = array(
1123 'suffix' => array(
1124 'title' => ' ' . $title,
1125 'name' => '__Copy_id_' . ($maxId + 1) . '_',
1126 ),
1127 );
1128
1129 $copy = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSet',
1130 array('id' => $id),
1131 NULL,
1132 $fieldsFix
1133 );
1134
1135 //copying all the blocks pertaining to the price set
1136 $copyPriceField = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceField',
1137 array('price_set_id' => $id),
1138 array('price_set_id' => $copy->id)
1139 );
1140 if (!empty($copyPriceField)) {
1141 $price = array_combine(self::getFieldIds($id), self::getFieldIds($copy->id));
1142
1143 //copy option group and values
1144 foreach ($price as $originalId => $copyId) {
1145 CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1146 array('price_field_id' => $originalId),
1147 array('price_field_id' => $copyId)
1148 );
1149 }
1150 }
1151 $copy->save();
1152
1153 CRM_Utils_Hook::copy('Set', $copy);
1154 return $copy;
1155 }
1156
1157 /**
1158 * check price set permission
1159 *
1160 * @param int $sid
1161 * The price set id.
1162 *
1163 * @return bool
1164 */
1165 public static function checkPermission($sid) {
1166 if ($sid && self::eventPriceSetDomainID()) {
1167 $domain_id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1168 if (CRM_Core_Config::domainID() != $domain_id) {
1169 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
1170 }
1171 }
1172 return TRUE;
1173 }
1174
1175 /**
1176 * Get the sum of participant count
1177 * for all fields of given price set.
1178 *
1179 * @param int $sid
1180 * The price set id.
1181 *
1182 * @param bool $onlyActive
1183 *
1184 * @return int|null|string
1185 * @static
1186 */
1187 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1188 $count = 0;
1189 if (!$sid) {
1190 return $count;
1191 }
1192
1193 $where = NULL;
1194 if ($onlyActive) {
1195 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1196 }
1197
1198 static $pricesetFieldCount = array();
1199 if (!isset($pricesetFieldCount[$sid])) {
1200 $sql = "
1201 SELECT sum(value.count) as totalCount
1202 FROM civicrm_price_field_value value
1203 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1204 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1205 WHERE pset.id = %1
1206 $where";
1207
1208 $count = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1209 $pricesetFieldCount[$sid] = ($count) ? $count : 0;
1210 }
1211
1212 return $pricesetFieldCount[$sid];
1213 }
1214
1215 /**
1216 * @param $ids
1217 *
1218 * @return array
1219 */
1220 public static function getMembershipCount($ids) {
1221 $queryString = "
1222 SELECT count( pfv.id ) AS count, pfv.id AS id
1223 FROM civicrm_price_field_value pfv
1224 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1225 WHERE pfv.id IN ( $ids )
1226 GROUP BY mt.member_of_contact_id";
1227
1228 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
1229 $count = array();
1230
1231 while ($crmDAO->fetch()) {
1232 $count[$crmDAO->id] = $crmDAO->count;
1233 }
1234
1235 return $count;
1236 }
1237
1238 /**
1239 * Check if auto renew option should be shown
1240 *
1241 * @param int $priceSetId
1242 * Price set id.
1243 *
1244 * @return int
1245 * $autoRenewOption ( 0:hide, 1:optional 2:required )
1246 */
1247 public static function checkAutoRenewForPriceSet($priceSetId) {
1248 // auto-renew option should be visible if membership types associated with all the fields has
1249 // been set for auto-renew option
1250 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1251
1252 // get the membership type auto renew option and check if required or optional
1253 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1254 FROM civicrm_price_field_value pfv
1255 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1256 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1257 WHERE pf.price_set_id = %1
1258 AND pf.is_active = 1
1259 AND pfv.is_active = 1';
1260
1261 $params = array(1 => array($priceSetId, 'Integer'));
1262
1263 $dao = CRM_Core_DAO::executeQuery($query, $params);
1264 $autoRenewOption = 2;
1265 $interval = $unit = array();
1266 while ($dao->fetch()) {
1267 if (!$dao->auto_renew) {
1268 $autoRenewOption = 0;
1269 break;
1270 }
1271 if ($dao->auto_renew == 1) {
1272 $autoRenewOption = 1;
1273 }
1274
1275 $interval[$dao->duration_interval] = $dao->duration_interval;
1276 $unit[$dao->duration_unit] = $dao->duration_unit;
1277 }
1278
1279 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1280 return $autoRenewOption;
1281 }
1282 else {
1283 return 0;
1284 }
1285 }
1286
1287 /**
1288 * Retrieve auto renew frequency and interval
1289 *
1290 * @param int $priceSetId
1291 * Price set id.
1292 *
1293 * @return array
1294 * associate array of frequency interval and unit
1295 * @static
1296 */
1297 public static function getRecurDetails($priceSetId) {
1298 $query = 'SELECT mt.duration_interval, mt.duration_unit
1299 FROM civicrm_price_field_value pfv
1300 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1301 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1302 WHERE pf.price_set_id = %1 LIMIT 1';
1303
1304 $params = array(1 => array($priceSetId, 'Integer'));
1305 $dao = CRM_Core_DAO::executeQuery($query, $params);
1306 $dao->fetch();
1307 return array($dao->duration_interval, $dao->duration_unit);
1308 }
1309
1310 /**
1311 * @return object
1312 */
1313 public static function eventPriceSetDomainID() {
1314 return CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME,
1315 'event_price_set_domain_id',
1316 NULL, FALSE
1317 );
1318 }
1319
1320 /**
1321 * Update the is_quick_config flag in the db
1322 *
1323 * @param int $id
1324 * Id of the database record.
1325 * @param bool $isQuickConfigValue we want to set the is_quick_config field.
1326 * Value we want to set the is_quick_config field.
1327 *
1328 * @return Object
1329 * DAO object on sucess, null otherwise
1330 * @static
1331 */
1332 public static function setIsQuickConfig($id, $isQuickConfig) {
1333 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1334 }
1335
1336 /**
1337 * Check if price set id provides option for
1338 * user to select both auto-renew and non-auto-renew memberships
1339 *
1340 * @static
1341 */
1342 public static function checkMembershipPriceSet($id) {
1343 $query =
1344 "
1345 SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1346 FROM civicrm_price_field_value pfv
1347 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1348 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1349 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1350 WHERE ps.id = %1
1351 ";
1352
1353 $params = array(1 => array($id, 'Integer'));
1354 $dao = CRM_Core_DAO::executeQuery($query, $params);
1355
1356 $autoRenew = array();
1357 //FIXME: do a comprehensive check of whether
1358 //2 membership types can be selected
1359 //instead of comparing all of them
1360 while ($dao->fetch()) {
1361 //temp fix for #CRM-10370
1362 //if its NULL consider it '0' i.e. 'No auto-renew option'
1363 $daoAutoRenew = $dao->auto_renew;
1364 if ($daoAutoRenew === NULL) {
1365 $daoAutoRenew = 0;
1366 }
1367 if (!empty($autoRenew) && !in_array($daoAutoRenew, $autoRenew)) {
1368 return TRUE;
1369 }
1370 $autoRenew[] = $daoAutoRenew;
1371 }
1372 return FALSE;
1373 }
1374
1375 /**
1376 * Copy priceSet when event/contibution page is copied
1377 *
1378 * @param string $baoName
1379 * BAO name.
1380 * @param int $id
1381 * Old event/contribution page id.
1382 * @param int $newId
1383 * Newly created event/contribution page id.
1384 */
1385 public static function copyPriceSet($baoName, $id, $newId) {
1386 $priceSetId = CRM_Price_BAO_PriceSet::getFor($baoName, $id);
1387 if ($priceSetId) {
1388 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1389 if ($isQuickConfig) {
1390 $copyPriceSet = &CRM_Price_BAO_PriceSet::copy($priceSetId);
1391 CRM_Price_BAO_PriceSet::addTo($baoName, $newId, $copyPriceSet->id);
1392 }
1393 else {
1394 $copyPriceSet = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1395 array(
1396 'entity_id' => $id,
1397 'entity_table' => $baoName,
1398 ),
1399 array('entity_id' => $newId)
1400 );
1401 }
1402 // copy event discount
1403 if ($baoName == 'civicrm_event') {
1404 $discount = CRM_Core_BAO_Discount::getOptionGroup($id, 'civicrm_event');
1405 foreach ($discount as $discountId => $setId) {
1406
1407 $copyPriceSet = &CRM_Price_BAO_PriceSet::copy($setId);
1408
1409 CRM_Core_DAO::copyGeneric(
1410 'CRM_Core_DAO_Discount',
1411 array(
1412 'id' => $discountId,
1413 ),
1414 array(
1415 'entity_id' => $newId,
1416 'price_set_id' => $copyPriceSet->id,
1417 )
1418 );
1419 }
1420 }
1421 }
1422 }
1423
1424 /*
1425 * Function to set tax_amount and tax_rate in LineItem
1426 */
1427 public static function setLineItem($field, $lineItem, $optionValueId) {
1428 if ($field['html_type'] == 'Text') {
1429 $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
1430 }
1431 else {
1432 $taxAmount = $field['options'][$optionValueId]['tax_amount'];
1433 }
1434 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1435 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1436 $lineItem[$optionValueId]['tax_rate'] = $taxRate;
1437
1438 return $lineItem;
1439 }
1440 }