Merge pull request #4897 from totten/master-cleanup2
[civicrm-core.git] / CRM / Price / BAO / PriceSet.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * Business object for managing price sets
38 *
39 */
40 class CRM_Price_BAO_PriceSet extends CRM_Price_DAO_PriceSet {
41
42 /**
43 * Static field for default price set details
44 *
45 * @var array
46 * @static
47 */
48 static $_defaultPriceSet = NULL;
49
50 /**
51 * Class constructor
52 */
53 public function __construct() {
54 parent::__construct();
55 }
56
57 /**
58 * Takes an associative array and creates a price set object
59 *
60 * @param array $params
61 * (reference) an assoc array of name/value pairs.
62 *
63 * @return CRM_Price_DAO_PriceSet object
64 * @static
65 */
66 public static function create(&$params) {
67 if (empty($params['id']) && empty($params['name'])) {
68 $params['name'] = CRM_Utils_String::munge($params['title'], '_', 242);
69 }
70 if (!empty($params['extends']) && is_array($params['extends'])) {
71 $params['extends'] = CRM_Utils_Array::implodePadded($params['extends']);
72 }
73 $priceSetBAO = new CRM_Price_BAO_PriceSet();
74 $priceSetBAO->copyValues($params);
75 if (self::eventPriceSetDomainID()) {
76 $priceSetBAO->domain_id = CRM_Core_Config::domainID();
77 }
78 return $priceSetBAO->save();
79 }
80
81 /**
82 * Fetch object based on array of properties
83 *
84 * @param array $params
85 * (reference ) an assoc array of name/value pairs.
86 * @param array $defaults
87 * (reference ) an assoc array to hold the flattened values.
88 *
89 * @return CRM_Price_DAO_PriceSet object
90 * @static
91 */
92 public static function retrieve(&$params, &$defaults) {
93 return CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
94 }
95
96 /**
97 * Update the is_active flag in the db
98 *
99 * @param int $id
100 * Id of the database record.
101 * @param $isActive
102 *
103 * @internal param bool $is_active value we want to set the is_active field
104 *
105 * @return Object
106 * DAO object on sucess, null otherwise
107 * @static
108 */
109 public static function setIsActive($id, $isActive) {
110 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
111 }
112
113 /**
114 * Calculate the default price set id
115 * assigned to the contribution/membership etc
116 *
117 * @param string $entity
118 *
119 * @return array
120 * default price set
121 *
122 * @static
123 */
124 public static function getDefaultPriceSet($entity = 'contribution') {
125 if (!empty(self::$_defaultPriceSet[$entity])) {
126 return self::$_defaultPriceSet[$entity];
127 }
128 $entityName = 'default_contribution_amount';
129 if ($entity == 'membership') {
130 $entityName = 'default_membership_type_amount';
131 }
132
133 $sql = "
134 SELECT ps.id AS setID, pfv.price_field_id AS priceFieldID, pfv.id AS priceFieldValueID, pfv.name, pfv.label, pfv.membership_type_id, pfv.amount, pfv.financial_type_id
135 FROM civicrm_price_set ps
136 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
137 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
138 WHERE ps.name = '{$entityName}'
139 ";
140
141 $dao = CRM_Core_DAO::executeQuery($sql);
142 self::$_defaultPriceSet[$entity] = array();
143 while ($dao->fetch()) {
144 self::$_defaultPriceSet[$entity][$dao->priceFieldValueID] = array(
145 'setID' => $dao->setID,
146 'priceFieldID' => $dao->priceFieldID,
147 'name' => $dao->name,
148 'label' => $dao->label,
149 'priceFieldValueID' => $dao->priceFieldValueID,
150 'membership_type_id' => $dao->membership_type_id,
151 'amount' => $dao->amount,
152 'financial_type_id' => $dao->financial_type_id,
153 );
154 }
155
156 return self::$_defaultPriceSet[$entity];
157 }
158
159 /**
160 * Get the price set title.
161 *
162 * @param int $id
163 * Id of price set.
164 *
165 * @return string
166 * title
167 *
168 * @static
169 */
170 public static function getTitle($id) {
171 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
172 }
173
174 /**
175 * Return a list of all forms which use this price set.
176 *
177 * @param int $id
178 * Id of price set.
179 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
180 *
181 * @return array
182 */
183 public static function &getUsedBy($id, $simpleReturn = FALSE) {
184 $usedBy = $forms = $tables = array();
185 $queryString = "
186 SELECT entity_table, entity_id
187 FROM civicrm_price_set_entity
188 WHERE price_set_id = %1";
189 $params = array(1 => array($id, 'Integer'));
190 $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
191
192 while ($crmFormDAO->fetch()) {
193 $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
194 $tables[] = $crmFormDAO->entity_table;
195 }
196 // Return only tables
197 if ($simpleReturn == 'table') {
198 return $tables;
199 }
200 if (empty($forms)) {
201 $queryString = "
202 SELECT cli.entity_table, cli.entity_id
203 FROM civicrm_line_item cli
204 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
205 WHERE cpf.price_set_id = %1";
206 $params = array(1 => array($id, 'Integer'));
207 $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
208 while ($crmFormDAO->fetch()) {
209 $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
210 $tables[] = $crmFormDAO->entity_table;
211 }
212 if (empty($forms)) {
213 return $usedBy;
214 }
215 }
216 // Return only entity data
217 if ($simpleReturn == 'entity') {
218 return $forms;
219 }
220 foreach ($forms as $table => $entities) {
221 switch ($table) {
222 case 'civicrm_event':
223 $ids = implode(',', $entities);
224 $queryString = "SELECT ce.id as id, ce.title as title, ce.is_public as isPublic, ce.start_date as startDate, ce.end_date as endDate, civicrm_option_value.label as eventType, ce.is_template as isTemplate, ce.template_title as templateTitle
225 FROM civicrm_event ce
226 LEFT JOIN civicrm_option_value ON
227 ( ce.event_type_id = civicrm_option_value.value )
228 LEFT JOIN civicrm_option_group ON
229 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
230 WHERE
231 civicrm_option_group.name = 'event_type' AND
232 ce.id IN ($ids) AND
233 ce.is_active = 1;";
234 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
235 while ($crmDAO->fetch()) {
236 if ($crmDAO->isTemplate) {
237 $usedBy['civicrm_event_template'][$crmDAO->id]['title'] = $crmDAO->templateTitle;
238 $usedBy['civicrm_event_template'][$crmDAO->id]['eventType'] = $crmDAO->eventType;
239 $usedBy['civicrm_event_template'][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
240 }
241 else {
242 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
243 $usedBy[$table][$crmDAO->id]['eventType'] = $crmDAO->eventType;
244 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
245 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
246 $usedBy[$table][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
247 }
248 }
249 break;
250
251 case 'civicrm_contribution_page':
252 $ids = implode(',', $entities);
253 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
254 FROM civicrm_contribution_page cp, civicrm_financial_type ct
255 WHERE ct.id = cp.financial_type_id AND
256 cp.id IN ($ids) AND
257 cp.is_active = 1;";
258 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
259 while ($crmDAO->fetch()) {
260 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
261 $usedBy[$table][$crmDAO->id]['type'] = $crmDAO->type;
262 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
263 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
264 }
265 break;
266
267 case 'civicrm_contribution':
268 case 'civicrm_membership':
269 case 'civicrm_participant':
270 $usedBy[$table] = 1;
271 break;
272
273 default:
274 CRM_Core_Error::fatal("$table is not supported in PriceSet::usedBy()");
275 break;
276 }
277 }
278
279 return $usedBy;
280 }
281
282 /**
283 * Delete the price set
284 *
285 * @param int $id
286 * Price Set id.
287 *
288 * @return boolean
289 * false if fields exist for this set, true if the
290 * set could be deleted
291 *
292 * @static
293 */
294 public static function deleteSet($id) {
295 // remove from all inactive forms
296 $usedBy = self::getUsedBy($id);
297 if (isset($usedBy['civicrm_event'])) {
298 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
299 $eventDAO = new CRM_Event_DAO_Event();
300 $eventDAO->id = $eventId;
301 $eventDAO->find();
302 while ($eventDAO->fetch()) {
303 self::removeFrom('civicrm_event', $eventDAO->id);
304 }
305 }
306 }
307
308 // delete price fields
309 $priceField = new CRM_Price_DAO_PriceField();
310 $priceField->price_set_id = $id;
311 $priceField->find();
312 while ($priceField->fetch()) {
313 // delete options first
314 CRM_Price_BAO_PriceField::deleteField($priceField->id);
315 }
316
317 $set = new CRM_Price_DAO_PriceSet();
318 $set->id = $id;
319 return $set->delete();
320 }
321
322 /**
323 * Link the price set with the specified table and id
324 *
325 * @param string $entityTable
326 * @param int $entityId
327 * @param int $priceSetId
328 *
329 * @return bool
330 */
331 public static function addTo($entityTable, $entityId, $priceSetId) {
332 // verify that the price set exists
333 $dao = new CRM_Price_DAO_PriceSet();
334 $dao->id = $priceSetId;
335 if (!$dao->find()) {
336 return FALSE;
337 }
338 unset($dao);
339
340 $dao = new CRM_Price_DAO_PriceSetEntity();
341 // find if this already exists
342 $dao->entity_id = $entityId;
343 $dao->entity_table = $entityTable;
344 $dao->find(TRUE);
345
346 // add or update price_set_id
347 $dao->price_set_id = $priceSetId;
348 return $dao->save();
349 }
350
351 /**
352 * Delete price set for the given entity and id
353 *
354 * @param string $entityTable
355 * @param int $entityId
356 *
357 * @return mixed
358 */
359 public static function removeFrom($entityTable, $entityId) {
360 $dao = new CRM_Price_DAO_PriceSetEntity();
361 $dao->entity_table = $entityTable;
362 $dao->entity_id = $entityId;
363 return $dao->delete();
364 }
365
366 /**
367 * Find a price_set_id associatied with the given table, id and usedFor
368 * Used For value for events:1, contribution:2, membership:3
369 *
370 * @param string $entityTable
371 * @param int $entityId
372 * @param int $usedFor
373 * ( price set that extends/used for particular component ).
374 *
375 * @param null $isQuickConfig
376 * @param null $setName
377 *
378 * @return integer|false price_set_id, or false if none found
379 */
380 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
381 if (!$entityTable || !$entityId) {
382 return FALSE;
383 }
384
385 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
386 FROM civicrm_price_set ps
387 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
388 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
389 if ($isQuickConfig) {
390 $sql .= ' AND ps.is_quick_config = 0 ';
391 }
392 $params = array(
393 1 => array($entityTable, 'String'),
394 2 => array($entityId, 'Integer'),
395 );
396 if ($usedFor) {
397 $sql .= " AND ps.extends LIKE '%%3%' ";
398 $params[3] = array($usedFor, 'Integer');
399 }
400
401 $dao = CRM_Core_DAO::executeQuery($sql, $params);
402 $dao->fetch();
403 $setName = (isset($dao->price_set_name)) ? $dao->price_set_name : FALSE;
404 return (isset($dao->price_set_id)) ? $dao->price_set_id : FALSE;
405 }
406
407 /**
408 * Find a price_set_id associated with the given option value or field ID
409 *
410 * @param array $params
411 * (reference) an assoc array of name/value pairs.
412 * array may contain either option id or
413 * price field id
414 *
415 * @return integer|NULL price set id on success, null otherwise
416 * @static
417 */
418 public static function getSetId(&$params) {
419 $fid = NULL;
420
421 if ($oid = CRM_Utils_Array::value('oid', $params)) {
422 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
423 $fieldValue->id = $oid;
424 if ($fieldValue->find(TRUE)) {
425 $fid = $fieldValue->price_field_id;
426 }
427 }
428 else {
429 $fid = CRM_Utils_Array::value('fid', $params);
430 }
431
432 if (isset($fid)) {
433 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
434 }
435
436 return NULL;
437 }
438
439 /**
440 * Return an associative array of all price sets
441 *
442 * @param bool $withInactive
443 * Whether or not to include inactive entries.
444 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
445 *
446 * @return array
447 * associative array of id => name
448 */
449 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE) {
450 $query = '
451 SELECT
452 DISTINCT ( price_set_id ) as id, title
453 FROM
454 civicrm_price_field,
455 civicrm_price_set
456 WHERE
457 civicrm_price_set.id = civicrm_price_field.price_set_id AND is_quick_config = 0 ';
458
459 if (!$withInactive) {
460 $query .= ' AND civicrm_price_set.is_active = 1 ';
461 }
462
463 if (self::eventPriceSetDomainID()) {
464 $query .= ' AND civicrm_price_set.domain_id = ' . CRM_Core_Config::domainID();
465 }
466
467 $priceSets = array();
468
469 if ($extendComponentName) {
470 $componentId = CRM_Core_Component::getComponentID($extendComponentName);
471 if (!$componentId) {
472 return $priceSets;
473 }
474 $query .= " AND civicrm_price_set.extends LIKE '%$componentId%' ";
475 }
476
477 $dao = CRM_Core_DAO::executeQuery($query);
478 while ($dao->fetch()) {
479 $priceSets[$dao->id] = $dao->title;
480 }
481 return $priceSets;
482 }
483
484 /**
485 * Get price set details
486 *
487 * An array containing price set details (including price fields) is returned
488 *
489 * @param int $setID
490 * @param bool $required
491 * @param bool $validOnly
492 *
493 * @internal param int $setId - price set id whose details are needed
494 *
495 * @return array
496 * array consisting of field details
497 */
498 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
499 // create a new tree
500 $setTree = array();
501
502 $priceFields = array(
503 'id',
504 'name',
505 'label',
506 'html_type',
507 'is_enter_qty',
508 'help_pre',
509 'help_post',
510 'weight',
511 'is_display_amounts',
512 'options_per_line',
513 'is_active',
514 'active_on',
515 'expire_on',
516 'javascript',
517 'visibility_id',
518 'is_required',
519 );
520 if ($required == TRUE) {
521 $priceFields[] = 'is_required';
522 }
523
524 // create select
525 $select = 'SELECT ' . implode(',', $priceFields);
526 $from = ' FROM civicrm_price_field';
527
528 $params = array();
529 $params[1] = array($setID, 'Integer');
530 $where = '
531 WHERE price_set_id = %1
532 AND is_active = 1
533 ';
534 $dateSelect = '';
535 if ($validOnly) {
536 $currentTime = date('YmdHis');
537 $dateSelect = "
538 AND ( active_on IS NULL OR active_on <= {$currentTime} )
539 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
540 ";
541 }
542
543 $orderBy = ' ORDER BY weight';
544
545 $sql = $select . $from . $where . $dateSelect . $orderBy;
546
547 $dao = CRM_Core_DAO::executeQuery($sql, $params);
548
549 $visibility = CRM_Core_PseudoConstant::visibility('name');
550 while ($dao->fetch()) {
551 $fieldID = $dao->id;
552
553 $setTree[$setID]['fields'][$fieldID] = array();
554 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
555
556 foreach ($priceFields as $field) {
557 if ($field == 'id' || is_null($dao->$field)) {
558 continue;
559 }
560
561 if ($field == 'visibility_id') {
562 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
563 }
564 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
565 }
566 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField::getOptions($fieldID, FALSE);
567 }
568
569 // also get the pre and post help from this price set
570 $sql = "
571 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
572 FROM civicrm_price_set
573 WHERE id = %1";
574 $dao = CRM_Core_DAO::executeQuery($sql, $params);
575 if ($dao->fetch()) {
576 $setTree[$setID]['extends'] = $dao->extends;
577 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id;
578 $setTree[$setID]['help_pre'] = $dao->help_pre;
579 $setTree[$setID]['help_post'] = $dao->help_post;
580 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config;
581 }
582 return $setTree;
583 }
584
585 /**
586 * Get the Price Field ID. We call this function when more than one being present would represent an error
587 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
588 * @param array $priceSet
589 *
590 * @throws CRM_Core_Exception
591 * @return int
592 */
593 public static function getOnlyPriceFieldID(array $priceSet) {
594 if (count($priceSet['fields']) > 1) {
595 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
596 }
597 return (int) implode('_', array_keys($priceSet['fields']));
598 }
599
600 /**
601 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
602 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
603 * @param array $priceSet
604 *
605 * @throws CRM_Core_Exception
606 * @return int
607 */
608 public static function getOnlyPriceFieldValueID(array $priceSet) {
609 $priceFieldID = self::getOnlyPriceFieldID($priceSet);
610 if (count($priceSet['fields'][$priceFieldID]['options']) > 1) {
611 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
612 }
613 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
614 }
615
616
617 /**
618 * @param CRM_Core_Form $form
619 * @param int $id
620 * @param string $entityTable
621 * @param bool $validOnly
622 * @param int $priceSetId
623 *
624 * @return bool|false|int|null
625 */
626 public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
627 if (!$priceSetId) {
628 $priceSetId = self::getFor($entityTable, $id);
629 }
630
631 //check if priceset is is_config
632 if (is_numeric($priceSetId)) {
633 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
634 $form->assign('quickConfig', 1);
635 }
636 }
637 // get price info
638 if ($priceSetId) {
639 if ($form->_action & CRM_Core_Action::UPDATE) {
640 $entityId = $entity = NULL;
641
642 switch ($entityTable) {
643 case 'civicrm_event':
644 $entity = 'participant';
645 if (CRM_Utils_System::getClassName($form) == 'CRM_Event_Form_Participant') {
646 $entityId = $form->_id;
647 }
648 else {
649 $entityId = $form->_participantId;
650 }
651 break;
652
653 case 'civicrm_contribution_page':
654 case 'civicrm_contribution':
655 $entity = 'contribution';
656 $entityId = $form->_id;
657 break;
658 }
659
660 if ($entityId && $entity) {
661 $form->_values['line_items'] = CRM_Price_BAO_LineItem::getLineItems($entityId, $entity);
662 }
663 $required = FALSE;
664 }
665 else {
666 $required = TRUE;
667 }
668
669 $form->_priceSetId = $priceSetId;
670 $priceSet = self::getSetDetail($priceSetId, $required, $validOnly);
671 $form->_priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
672 $form->_values['fee'] = CRM_Utils_Array::value('fields', $form->_priceSet);
673
674 //get the price set fields participant count.
675 if ($entityTable == 'civicrm_event') {
676 //get option count info.
677 $form->_priceSet['optionsCountTotal'] = self::getPricesetCount($priceSetId);
678 if ($form->_priceSet['optionsCountTotal']) {
679 $optionsCountDeails = array();
680 if (!empty($form->_priceSet['fields'])) {
681 foreach ($form->_priceSet['fields'] as $field) {
682 foreach ($field['options'] as $option) {
683 $count = CRM_Utils_Array::value('count', $option, 0);
684 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
685 }
686 }
687 }
688 $form->_priceSet['optionsCountDetails'] = $optionsCountDeails;
689 }
690
691 //get option max value info.
692 $optionsMaxValueTotal = 0;
693 $optionsMaxValueDetails = array();
694
695 if (!empty($form->_priceSet['fields'])) {
696 foreach ($form->_priceSet['fields'] as $field) {
697 foreach ($field['options'] as $option) {
698 $maxVal = CRM_Utils_Array::value('max_value', $option, 0);
699 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
700 $optionsMaxValueTotal += $maxVal;
701 }
702 }
703 }
704
705 $form->_priceSet['optionsMaxValueTotal'] = $optionsMaxValueTotal;
706 if ($optionsMaxValueTotal) {
707 $form->_priceSet['optionsMaxValueDetails'] = $optionsMaxValueDetails;
708 }
709 }
710 $form->set('priceSetId', $form->_priceSetId);
711 $form->set('priceSet', $form->_priceSet);
712
713 return $priceSetId;
714 }
715 return FALSE;
716 }
717
718 /**
719 * @param $fields
720 * @param array $params
721 * @param $lineItem
722 * @param string $component
723 */
724 public static function processAmount(&$fields, &$params, &$lineItem, $component = '') {
725 // using price set
726 $totalPrice = $totalTax = 0;
727 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
728 if ($component) {
729 $autoRenew = array();
730 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
731 }
732 foreach ($fields as $id => $field) {
733 if (empty($params["price_{$id}"]) ||
734 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
735 ) {
736 // skip if nothing was submitted for this field
737 continue;
738 }
739
740 switch ($field['html_type']) {
741 case 'Text':
742 $firstOption = reset($field['options']);
743 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
744 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
745 if (CRM_Utils_Array::value('tax_rate', $field['options'][key($field['options'])])) {
746 $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
747 $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
748 }
749 if (CRM_Utils_Array::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
750 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
751 if (array_key_exists($params['financial_type_id'], $taxRates)) {
752 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
753 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
754 $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
755 $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
756 $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
757 }
758 }
759 $totalPrice += $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[key($field['options'])]);
760 break;
761
762 case 'Radio':
763 //special case if user select -none-
764 if ($params["price_{$id}"] <= 0) {
765 continue;
766 }
767 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
768 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
769 $optionLabel = CRM_Utils_Array::value('label', $field['options'][$optionValueId]);
770 $params['amount_priceset_level_radio'] = array();
771 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
772 if (isset($radioLevel)) {
773 $radioLevel = array_merge($radioLevel,
774 array_keys($params['amount_priceset_level_radio'])
775 );
776 }
777 else {
778 $radioLevel = array_keys($params['amount_priceset_level_radio']);
779 }
780 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
781 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
782 $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
783 $totalTax += $field['options'][$optionValueId]['tax_amount'];
784 if (CRM_Utils_Array::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
785 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
786 }
787 }
788 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
789 if (
790 $component &&
791 // auto_renew exists and is empty in some workflows, which php treat as a 0
792 // and hence we explicitly check to see if auto_renew is numeric
793 isset($lineItem[$optionValueId]['auto_renew']) &&
794 is_numeric($lineItem[$optionValueId]['auto_renew'])
795 ) {
796 $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
797 }
798 break;
799
800 case 'Select':
801 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
802 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
803 $optionLabel = $field['options'][$optionValueId]['label'];
804 $params['amount_priceset_level_select'] = array();
805 $params['amount_priceset_level_select'][CRM_Utils_Array::key(1, $params["price_{$id}"])] = $optionLabel;
806 if (isset($selectLevel)) {
807 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
808 }
809 else {
810 $selectLevel = array_keys($params['amount_priceset_level_select']);
811 }
812 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
813 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
814 $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
815 $totalTax += $field['options'][$optionValueId]['tax_amount'];
816 }
817 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
818 if (
819 $component &&
820 isset($lineItem[$optionValueId]['auto_renew']) &&
821 is_numeric($lineItem[$optionValueId]['auto_renew'])
822 ) {
823 $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
824 }
825 break;
826
827 case 'CheckBox':
828 $params['amount_priceset_level_checkbox'] = $optionIds = array();
829 foreach ($params["price_{$id}"] as $optionId => $option) {
830 $optionIds[] = $optionId;
831 $optionLabel = $field['options'][$optionId]['label'];
832 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
833 if (isset($checkboxLevel)) {
834 $checkboxLevel = array_unique(array_merge(
835 $checkboxLevel,
836 array_keys($params['amount_priceset_level_checkbox'])
837 )
838 );
839 }
840 else {
841 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
842 }
843 }
844 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
845 foreach ($optionIds as $optionId) {
846 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionId])) {
847 $lineItem = self::setLineItem($field, $lineItem, $optionId);
848 $totalTax += $field['options'][$optionId]['tax_amount'];
849 }
850 $totalPrice += $lineItem[$optionId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionId]);
851 if (
852 $component &&
853 isset($lineItem[$optionId]['auto_renew']) &&
854 is_numeric($lineItem[$optionId]['auto_renew'])
855 ) {
856 $autoRenew[$lineItem[$optionId]['auto_renew']] += $lineItem[$optionId]['line_total'];
857 }
858 }
859 break;
860 }
861 }
862
863 $amount_level = array();
864 $totalParticipant = 0;
865 if (is_array($lineItem)) {
866 foreach ($lineItem as $values) {
867 $totalParticipant += $values['participant_count'];
868 if ($values['html_type'] == 'Text') {
869 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
870 continue;
871 }
872 $amount_level[] = $values['label'];
873 }
874 }
875
876 $displayParticipantCount = '';
877 if ($totalParticipant > 0) {
878 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
879 }
880 $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
881 $params['amount'] = $totalPrice;
882 $params['tax_amount'] = $totalTax;
883 if ($component) {
884 foreach ($autoRenew as $dontCare => $eachAmount) {
885 if (!$eachAmount) {
886 unset($autoRenew[$dontCare]);
887 }
888 }
889 if (count($autoRenew) > 1) {
890 $params['autoRenew'] = $autoRenew;
891 }
892 }
893 }
894
895 /**
896 * Build the price set form.
897 *
898 * @param CRM_Core_Form $form
899 *
900 * @return void
901 */
902 public static function buildPriceSet(&$form) {
903 $priceSetId = $form->get('priceSetId');
904 if (!$priceSetId) {
905 return;
906 }
907
908 $validFieldsOnly = TRUE;
909 $className = CRM_Utils_System::getClassName($form);
910 if (in_array($className, array(
911 'CRM_Contribute_Form_Contribution',
912 'CRM_Member_Form_Membership'
913 ))) {
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 /**
1087 * Get field ids of a price set
1088 *
1089 * @param int $id
1090 * Price Set id.
1091 *
1092 * @return array
1093 * of the field ids
1094 *
1095 * @static
1096 */
1097 public static function getFieldIds($id) {
1098 $priceField = new CRM_Price_DAO_PriceField();
1099 $priceField->price_set_id = $id;
1100 $priceField->find();
1101 while ($priceField->fetch()) {
1102 $var[] = $priceField->id;
1103 }
1104 return $var;
1105 }
1106
1107 /**
1108 * make a copy of a price set, including
1109 * all the fields
1110 *
1111 * @param int $id
1112 * The price set id to copy.
1113 *
1114 * @return the copy object
1115 * @static
1116 */
1117 public static function copy($id) {
1118 $maxId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1119
1120 $title = ts('[Copy id %1]', array(1 => $maxId + 1));
1121 $fieldsFix = array(
1122 'suffix' => array(
1123 'title' => ' ' . $title,
1124 'name' => '__Copy_id_' . ($maxId + 1) . '_',
1125 ),
1126 );
1127
1128 $copy = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSet',
1129 array('id' => $id),
1130 NULL,
1131 $fieldsFix
1132 );
1133
1134 //copying all the blocks pertaining to the price set
1135 $copyPriceField = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceField',
1136 array('price_set_id' => $id),
1137 array('price_set_id' => $copy->id)
1138 );
1139 if (!empty($copyPriceField)) {
1140 $price = array_combine(self::getFieldIds($id), self::getFieldIds($copy->id));
1141
1142 //copy option group and values
1143 foreach ($price as $originalId => $copyId) {
1144 CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1145 array('price_field_id' => $originalId),
1146 array('price_field_id' => $copyId)
1147 );
1148 }
1149 }
1150 $copy->save();
1151
1152 CRM_Utils_Hook::copy('Set', $copy);
1153 return $copy;
1154 }
1155
1156 /**
1157 * check price set permission
1158 *
1159 * @param int $sid
1160 * The price set id.
1161 *
1162 * @return bool
1163 */
1164 public static function checkPermission($sid) {
1165 if ($sid && self::eventPriceSetDomainID()) {
1166 $domain_id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1167 if (CRM_Core_Config::domainID() != $domain_id) {
1168 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
1169 }
1170 }
1171 return TRUE;
1172 }
1173
1174 /**
1175 * Get the sum of participant count
1176 * for all fields of given price set.
1177 *
1178 * @param int $sid
1179 * The price set id.
1180 *
1181 * @param bool $onlyActive
1182 *
1183 * @return int|null|string
1184 * @static
1185 */
1186 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1187 $count = 0;
1188 if (!$sid) {
1189 return $count;
1190 }
1191
1192 $where = NULL;
1193 if ($onlyActive) {
1194 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1195 }
1196
1197 static $pricesetFieldCount = array();
1198 if (!isset($pricesetFieldCount[$sid])) {
1199 $sql = "
1200 SELECT sum(value.count) as totalCount
1201 FROM civicrm_price_field_value value
1202 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1203 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1204 WHERE pset.id = %1
1205 $where";
1206
1207 $count = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1208 $pricesetFieldCount[$sid] = ($count) ? $count : 0;
1209 }
1210
1211 return $pricesetFieldCount[$sid];
1212 }
1213
1214 /**
1215 * @param $ids
1216 *
1217 * @return array
1218 */
1219 public static function getMembershipCount($ids) {
1220 $queryString = "
1221 SELECT count( pfv.id ) AS count, pfv.id AS id
1222 FROM civicrm_price_field_value pfv
1223 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1224 WHERE pfv.id IN ( $ids )
1225 GROUP BY mt.member_of_contact_id";
1226
1227 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
1228 $count = array();
1229
1230 while ($crmDAO->fetch()) {
1231 $count[$crmDAO->id] = $crmDAO->count;
1232 }
1233
1234 return $count;
1235 }
1236
1237 /**
1238 * Check if auto renew option should be shown
1239 *
1240 * @param int $priceSetId
1241 * Price set id.
1242 *
1243 * @return int
1244 * $autoRenewOption ( 0:hide, 1:optional 2:required )
1245 */
1246 public static function checkAutoRenewForPriceSet($priceSetId) {
1247 // auto-renew option should be visible if membership types associated with all the fields has
1248 // been set for auto-renew option
1249 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1250
1251 // get the membership type auto renew option and check if required or optional
1252 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1253 FROM civicrm_price_field_value pfv
1254 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1255 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1256 WHERE pf.price_set_id = %1
1257 AND pf.is_active = 1
1258 AND pfv.is_active = 1';
1259
1260 $params = array(1 => array($priceSetId, 'Integer'));
1261
1262 $dao = CRM_Core_DAO::executeQuery($query, $params);
1263 $autoRenewOption = 2;
1264 $interval = $unit = array();
1265 while ($dao->fetch()) {
1266 if (!$dao->auto_renew) {
1267 $autoRenewOption = 0;
1268 break;
1269 }
1270 if ($dao->auto_renew == 1) {
1271 $autoRenewOption = 1;
1272 }
1273
1274 $interval[$dao->duration_interval] = $dao->duration_interval;
1275 $unit[$dao->duration_unit] = $dao->duration_unit;
1276 }
1277
1278 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1279 return $autoRenewOption;
1280 }
1281 else {
1282 return 0;
1283 }
1284 }
1285
1286 /**
1287 * Retrieve auto renew frequency and interval
1288 *
1289 * @param int $priceSetId
1290 * Price set id.
1291 *
1292 * @return array
1293 * associate array of frequency interval and unit
1294 * @static
1295 */
1296 public static function getRecurDetails($priceSetId) {
1297 $query = 'SELECT mt.duration_interval, mt.duration_unit
1298 FROM civicrm_price_field_value pfv
1299 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1300 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1301 WHERE pf.price_set_id = %1 LIMIT 1';
1302
1303 $params = array(1 => array($priceSetId, 'Integer'));
1304 $dao = CRM_Core_DAO::executeQuery($query, $params);
1305 $dao->fetch();
1306 return array($dao->duration_interval, $dao->duration_unit);
1307 }
1308
1309 /**
1310 * @return object
1311 */
1312 public static function eventPriceSetDomainID() {
1313 return CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME,
1314 'event_price_set_domain_id',
1315 NULL, FALSE
1316 );
1317 }
1318
1319 /**
1320 * Update the is_quick_config flag in the db
1321 *
1322 * @param int $id
1323 * Id of the database record.
1324 * @param bool $isQuickConfigValue we want to set the is_quick_config field.
1325 * Value we want to set the is_quick_config field.
1326 *
1327 * @return Object
1328 * DAO object on sucess, null otherwise
1329 * @static
1330 */
1331 public static function setIsQuickConfig($id, $isQuickConfig) {
1332 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1333 }
1334
1335 /**
1336 * Check if price set id provides option for
1337 * user to select both auto-renew and non-auto-renew memberships
1338 *
1339 * @static
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 public static function setLineItem($field, $lineItem, $optionValueId) {
1427 if ($field['html_type'] == 'Text') {
1428 $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
1429 }
1430 else {
1431 $taxAmount = $field['options'][$optionValueId]['tax_amount'];
1432 }
1433 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1434 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1435 $lineItem[$optionValueId]['tax_rate'] = $taxRate;
1436
1437 return $lineItem;
1438 }
1439 }