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