Merge pull request #796 from kurund/CRM-12589
[civicrm-core.git] / CRM / Price / BAO / Set.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
32 * $Id$
33 *
34 */
35
36/**
37 * Business object for managing price sets
38 *
39 */
40class CRM_Price_BAO_Set extends CRM_Price_DAO_Set {
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_Set object
55 * @access public
56 * @static
57 */
58 static function create(&$params) {
59 $priceSetBAO = new CRM_Price_BAO_Set();
60 $priceSetBAO->copyValues($params);
61 if (self::eventPriceSetDomainID()) {
62 $priceSetBAO->domain_id = CRM_Core_Config::domainID();
63 }
64 return $priceSetBAO->save();
65 }
66
67 /**
68 * Takes a bunch of params that are needed to match certain criteria and
69 * retrieves the relevant objects. Typically the valid params are only
70 * contact_id. We'll tweak this function to be more full featured over a period
71 * of time. This is the inverse function of create. It also stores all the retrieved
72 * values in the default array
73 *
74 * @param array $params (reference ) an assoc array of name/value pairs
75 * @param array $defaults (reference ) an assoc array to hold the flattened values
76 *
77 * @return object CRM_Price_DAO_Set object
78 * @access public
79 * @static
80 */
81 static function retrieve(&$params, &$defaults) {
82 return CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_Set', $params, $defaults);
83 }
84
85 /**
86 * update the is_active flag in the db
87 *
88 * @param int $id id of the database record
89 * @param boolean $is_active value we want to set the is_active field
90 *
91 * @return Object DAO object on sucess, null otherwise
92 * @static
93 * @access public
94 */
95 static function setIsActive($id, $isActive) {
96 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_Set', $id, 'is_active', $isActive);
97 }
98
99 /**
100 * Calculate the default price set id
101 * assigned to the contribution/membership etc
102 *
103 * @param string $entity
104 *
105 * @return id $priceSetID
106 *
107 * @access public
108 * @static
109 *
110 */
111 public static function getDefaultPriceSet($entity = 'contribution') {
112 if ($entity == 'contribution') {
113 $entityName = 'default_contribution_amount';
114 }
115 else if ($entity == 'membership') {
116 $entityName = 'default_membership_type_amount';
117 }
118
119 $sql = "
120SELECT ps.id AS setID, pfv.price_field_id AS priceFieldID, pfv.id AS priceFieldValueID, pfv.name, pfv.label
121FROM civicrm_price_set ps
122LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
123LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
124WHERE ps.name = '{$entityName}'
125";
126
127 $dao = CRM_Core_DAO::executeQuery($sql);
128 $defaultPriceSet = array();
129 while ($dao->fetch()) {
130 $defaultPriceSet[$dao->priceFieldValueID]['setID'] = $dao->setID;
131 $defaultPriceSet[$dao->priceFieldValueID]['priceFieldID'] = $dao->priceFieldID;
132 $defaultPriceSet[$dao->priceFieldValueID]['name'] = $dao->name;
133 $defaultPriceSet[$dao->priceFieldValueID]['label'] = $dao->label;
134 $defaultPriceSet[$dao->priceFieldValueID]['priceFieldValueID'] = $dao->priceFieldValueID;
135 }
136
137 return $defaultPriceSet;
138 }
139
140 /**
141 * Get the price set title.
142 *
143 * @param int $id id of price set
144 *
145 * @return string title
146 *
147 * @access public
148 * @static
149 *
150 */
151 public static function getTitle($id) {
152 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $id, 'title');
153 }
154
155 /**
156 * Return a list of all forms which use this price set.
157 *
158 * @param int $id id of price set
159 * @param str $simpleReturn - get raw data. Possible values: 'entity', 'table'
160 *
161 * @return array
162 */
163 public static function &getUsedBy($id, $simpleReturn = FALSE) {
164 $usedBy = $forms = $tables = array();
165 $queryString = "
166SELECT entity_table, entity_id
167FROM civicrm_price_set_entity
168WHERE price_set_id = %1";
169 $params = array(1 => array($id, 'Integer'));
170 $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
171
172 while ($crmFormDAO->fetch()) {
173 $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
174 $tables[] = $crmFormDAO->entity_table;
175 }
176 // Return only tables
177 if ($simpleReturn == 'table') {
178 return $tables;
179 }
180 if (empty($forms)) {
181 $queryString = "
182SELECT cli.entity_table, cli.entity_id
183FROM civicrm_line_item cli
184LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
185WHERE cpf.price_set_id = %1";
186 $params = array(1 => array($id, 'Integer'));
187 $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
188 while ($crmFormDAO->fetch()) {
189 $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
190 $tables[] = $crmFormDAO->entity_table;
191 }
192 if (empty($forms)) {
193 return $usedBy;
194 }
195 }
196 // Return only entity data
197 if ($simpleReturn == 'entity') {
198 return $forms;
199 }
200 foreach ($forms as $table => $entities) {
201 switch ($table) {
202 case 'civicrm_event':
203 $ids = implode(',', $entities);
204 $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
205FROM civicrm_event ce
206LEFT JOIN civicrm_option_value ON
207 ( ce.event_type_id = civicrm_option_value.value )
208LEFT JOIN civicrm_option_group ON
209 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
210WHERE
211 civicrm_option_group.name = 'event_type' AND
212 ( ce.is_template IS NULL OR ce.is_template = 0) AND
213 ce.id IN ($ids) AND
214 ce.is_active = 1;";
215 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
216 while ($crmDAO->fetch()) {
217 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
218 $usedBy[$table][$crmDAO->id]['eventType'] = $crmDAO->eventType;
219 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
220 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
221 $usedBy[$table][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
222 }
223 break;
224
225 case 'civicrm_contribution_page':
226 $ids = implode(',', $entities);
227 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
228FROM civicrm_contribution_page cp, civicrm_financial_type ct
cde484fd 229WHERE ct.id = cp.financial_type_id AND
6a488035
TO
230 cp.id IN ($ids) AND
231 cp.is_active = 1;";
232 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
233 while ($crmDAO->fetch()) {
234 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
235 $usedBy[$table][$crmDAO->id]['type'] = $crmDAO->type;
236 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
237 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
238 }
239 break;
240
241 case 'civicrm_contribution':
242 case 'civicrm_membership':
243 case 'civicrm_participant':
244 $usedBy[$table] = 1;
245 break;
246
247 default:
248 CRM_Core_Error::fatal("$table is not supported in PriceSet::usedBy()");
249 break;
250 }
251 }
252
253 return $usedBy;
254 }
255
256 /**
257 * Delete the price set
258 *
259 * @param int $id Price Set id
260 *
261 * @return boolean false if fields exist for this set, true if the
262 * set could be deleted
263 *
264 * @access public
265 * @static
266 */
267 public static function deleteSet($id) {
268 // remove from all inactive forms
269 $usedBy = self::getUsedBy($id);
270 if (isset($usedBy['civicrm_event'])) {
271 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
272 $eventDAO = new CRM_Event_DAO_Event();
273 $eventDAO->id = $eventId;
274 $eventDAO->find();
275 while ($eventDAO->fetch()) {
276 self::removeFrom('civicrm_event', $eventDAO->id);
277 }
278 }
279 }
280
281 // delete price fields
282 $priceField = new CRM_Price_DAO_Field();
283 $priceField->price_set_id = $id;
284 $priceField->find();
285 while ($priceField->fetch()) {
286 // delete options first
287 CRM_Price_BAO_Field::deleteField($priceField->id);
288 }
289
290 $set = new CRM_Price_DAO_Set();
291 $set->id = $id;
292 return $set->delete();
293 }
294
295 /**
296 * Link the price set with the specified table and id
297 *
298 * @param string $entityTable
299 * @param integer $entityId
300 * @param integer $priceSetId
301 *
302 * @return bool
303 */
304 public static function addTo($entityTable, $entityId, $priceSetId) {
305 // verify that the price set exists
306 $dao = new CRM_Price_DAO_Set();
307 $dao->id = $priceSetId;
308 if (!$dao->find()) {
309 return FALSE;
310 }
311 unset($dao);
312
313 $dao = new CRM_Price_DAO_SetEntity();
314 // find if this already exists
315 $dao->entity_id = $entityId;
316 $dao->entity_table = $entityTable;
317 $dao->find(TRUE);
318
319 // add or update price_set_id
320 $dao->price_set_id = $priceSetId;
321 return $dao->save();
322 }
323
324 /**
325 * Delete price set for the given entity and id
326 *
327 * @param string $entityTable
328 * @param integer $entityId
329 */
330 public static function removeFrom($entityTable, $entityId) {
331 $dao = new CRM_Price_DAO_SetEntity();
332 $dao->entity_table = $entityTable;
333 $dao->entity_id = $entityId;
334 return $dao->delete();
335 }
336
337 /**
338 * Find a price_set_id associatied with the given table, id and usedFor
339 * Used For value for events:1, contribution:2, membership:3
340 *
341 * @param string $entityTable
342 * @param int $entityId
343 * @param int $usedFor ( price set that extends/used for particular component )
344 *
345 * @return integer|false price_set_id, or false if none found
346 */
347 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
348 if (!$entityTable || !$entityId) {
349 return FALSE;
350 }
351
352 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
353 FROM civicrm_price_set ps
354 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
355 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
356 if ($isQuickConfig) {
357 $sql .= ' AND ps.is_quick_config = 0 ';
358 }
359 $params = array(1 => array($entityTable, 'String'),
360 2 => array($entityId, 'Integer'),
361 );
362 if ($usedFor) {
363 $sql .= " AND ps.extends LIKE '%%3%' ";
364 $params[3] = array($usedFor, 'Integer');
365 }
366
367 $dao = CRM_Core_DAO::executeQuery($sql, $params);
368 $dao->fetch();
369 $setName = (isset($dao->price_set_name)) ? $dao->price_set_name : FALSE;
370 return (isset($dao->price_set_id)) ? $dao->price_set_id : FALSE;
371 }
372
373 /**
374 * Find a price_set_id associatied with the given option value or field ID
375 *
376 * @param array $params (reference) an assoc array of name/value pairs
377 * array may contain either option id or
378 * price field id
379 *
380 * @return price set id on success, null otherwise
381 * @static
382 * @access public
383 */
384 public static function getSetId(&$params) {
385 $fid = NULL;
386
387 if ($oid = CRM_Utils_Array::value('oid', $params)) {
388 $fieldValue = new CRM_Price_DAO_FieldValue();
389 $fieldValue->id = $oid;
390 if ($fieldValue->find(TRUE)) {
391 $fid = $fieldValue->price_field_id;
392 }
393 }
394 else {
395 $fid = CRM_Utils_Array::value('fid', $params);
396 }
397
398 if (isset($fid)) {
399 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $fid, 'price_set_id');
400 }
401
402 return NULL;
403 }
404
405 /**
406 * Return an associative array of all price sets
407 *
408 * @param bool $withInactive whether or not to include inactive entries
409 * @param string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
410 *
411 * @return array associative array of id => name
412 */
413 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE) {
414 $query = '
415 SELECT
416 DISTINCT ( price_set_id ) as id, title
417 FROM
418 civicrm_price_field,
419 civicrm_price_set
420 WHERE
421 civicrm_price_set.id = civicrm_price_field.price_set_id AND is_quick_config = 0 ';
422
423 if (!$withInactive) {
424 $query .= ' AND civicrm_price_set.is_active = 1 ';
425 }
426
427 if (self::eventPriceSetDomainID()) {
428 $query .= ' AND civicrm_price_set.domain_id = ' . CRM_Core_Config::domainID();
429 }
430
431 $priceSets = array();
432
433 if ($extendComponentName) {
434 $componentId = CRM_Core_Component::getComponentID($extendComponentName);
435 if (!$componentId) {
436 return $priceSets;
437 }
438 $query .= " AND civicrm_price_set.extends LIKE '%$componentId%' ";
439 }
440
441 $dao = CRM_Core_DAO::executeQuery($query);
442 while ($dao->fetch()) {
443 $priceSets[$dao->id] = $dao->title;
444 }
445 return $priceSets;
446 }
447
448 /**
449 * Get price set details
450 *
451 * An array containing price set details (including price fields) is returned
452 *
453 * @param int $setId - price set id whose details are needed
454 *
455 * @return array $setTree - array consisting of field details
456 */
457 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
458 // create a new tree
459 $setTree = array();
460 $select = $from = $where = $orderBy = '';
461
462 $priceFields = array(
463 'id',
464 'name',
465 'label',
466 'html_type',
467 'is_enter_qty',
468 'help_pre',
469 'help_post',
470 'weight',
471 'is_display_amounts',
472 'options_per_line',
473 'is_active',
474 'active_on',
475 'expire_on',
476 'javascript',
477 'visibility_id',
478 'is_required',
479 );
480 if ($required == TRUE) {
481 $priceFields[] = 'is_required';
482 }
483
484 // create select
485 $select = 'SELECT ' . implode(',', $priceFields);
486 $from = ' FROM civicrm_price_field';
487
488 $params = array();
489 $params[1] = array($setID, 'Integer');
490 $where = '
491WHERE price_set_id = %1
492AND is_active = 1
493';
494 $dateSelect = '';
495 if ($validOnly) {
496 $currentTime = date('YmdHis');
497 $dateSelect = "
498AND ( active_on IS NULL OR active_on <= {$currentTime} )
499AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
500";
501 }
502
503 $orderBy = ' ORDER BY weight';
504
505 $sql = $select . $from . $where . $dateSelect . $orderBy;
506
507 $dao = CRM_Core_DAO::executeQuery($sql, $params);
508
509 $visibility = CRM_Core_PseudoConstant::visibility('name');
510 while ($dao->fetch()) {
511 $fieldID = $dao->id;
512
513 $setTree[$setID]['fields'][$fieldID] = array();
514 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
515
516 foreach ($priceFields as $field) {
517 if ($field == 'id' || is_null($dao->$field)) {
518 continue;
519 }
520
521 if ($field == 'visibility_id') {
522 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
523 }
524 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
525 }
526 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_Field::getOptions($fieldID, FALSE);
527 }
528
529 // also get the pre and post help from this price set
530 $sql = "
531SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
532FROM civicrm_price_set
533WHERE id = %1";
534 $dao = CRM_Core_DAO::executeQuery($sql, $params);
535 if ($dao->fetch()) {
536 $setTree[$setID]['extends'] = $dao->extends;
537 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id;
538 $setTree[$setID]['help_pre'] = $dao->help_pre;
539 $setTree[$setID]['help_post'] = $dao->help_post;
540 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config;
541 }
542 return $setTree;
543 }
544
545 static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
546 if (!$priceSetId) {
547 $priceSetId = self::getFor($entityTable, $id);
548 }
549
550 //check if priceset is is_config
551 if (is_numeric($priceSetId)) {
552 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
553 $form->assign('quickConfig', 1);
554 }
555 }
556 // get price info
557 if ($priceSetId) {
558 if ($form->_action & CRM_Core_Action::UPDATE) {
559 $entityId = $entity = NULL;
560
561 switch ($entityTable) {
562 case 'civicrm_event':
563 $entity = 'participant';
564 if (CRM_Utils_System::getClassName($form) == 'CRM_Event_Form_Participant') {
565 $entityId = $form->_id;
566 }
567 else {
568 $entityId = $form->_participantId;
569 }
570 break;
571
572 case 'civicrm_contribution_page':
573 case 'civicrm_contribution':
574 $entity = 'contribution';
575 $entityId = $form->_id;
576 break;
577 }
578
579 if ($entityId && $entity) {
580 $form->_values['line_items'] = CRM_Price_BAO_LineItem::getLineItems($entityId, $entity);
581 }
582 $required = FALSE;
583 }
584 else {
585 $required = TRUE;
586 }
587
588 $form->_priceSetId = $priceSetId;
589 $priceSet = self::getSetDetail($priceSetId, $required, $validOnly);
590 $form->_priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
591 $form->_values['fee'] = CRM_Utils_Array::value('fields', $form->_priceSet);
592
593 //get the price set fields participant count.
594 if ($entityTable == 'civicrm_event') {
595 //get option count info.
596 $form->_priceSet['optionsCountTotal'] = self::getPricesetCount($priceSetId);
597 if ($form->_priceSet['optionsCountTotal']) {
598 $optionsCountDeails = array();
599 if (!empty($form->_priceSet['fields'])) {
600 foreach ($form->_priceSet['fields'] as $field) {
601 foreach ($field['options'] as $option) {
602 $count = CRM_Utils_Array::value('count', $option, 0);
603 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
604 }
605 }
606 }
607 $form->_priceSet['optionsCountDetails'] = $optionsCountDeails;
608 }
609
610 //get option max value info.
611 $optionsMaxValueTotal = 0;
612 $optionsMaxValueDetails = array();
613
614 if (!empty($form->_priceSet['fields'])) {
615 foreach ($form->_priceSet['fields'] as $field) {
616 foreach ($field['options'] as $option) {
617 $maxVal = CRM_Utils_Array::value('max_value', $option, 0);
618 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
619 $optionsMaxValueTotal += $maxVal;
620 }
621 }
622 }
623
624 $form->_priceSet['optionsMaxValueTotal'] = $optionsMaxValueTotal;
625 if ($optionsMaxValueTotal) {
626 $form->_priceSet['optionsMaxValueDetails'] = $optionsMaxValueDetails;
627 }
628 }
629 $form->set('priceSetId', $form->_priceSetId);
630 $form->set('priceSet', $form->_priceSet);
631
632 return $priceSetId;
633 }
634 return FALSE;
635 }
636
637 static function processAmount(&$fields, &$params, &$lineItem, $component = '') {
638 // using price set
639 $totalPrice = 0;
640 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
641 if ($component) {
642 $autoRenew = array();
643 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
644 }
645 foreach ($fields as $id => $field) {
646 if (!CRM_Utils_Array::value("price_{$id}", $params) ||
647 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
648 ) {
649 // skip if nothing was submitted for this field
650 continue;
651 }
652
653 switch ($field['html_type']) {
654 case 'Text':
655 $params["price_{$id}"] = array(key($field['options']) => $params["price_{$id}"]);
656 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
657 $totalPrice += $lineItem[key($field['options'])]['line_total'];
658 break;
659
660 case 'Radio':
661 //special case if user select -none-
662 if ($params["price_{$id}"] <= 0) {
663 continue;
664 }
665 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
666 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
667 $optionLabel = CRM_Utils_Array::value('label', $field['options'][$optionValueId]);
668 $params['amount_priceset_level_radio'] = array();
669 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
670 if (isset($radioLevel)) {
671 $radioLevel = array_merge($radioLevel,
672 array_keys($params['amount_priceset_level_radio'])
673 );
674 }
675 else {
676 $radioLevel = array_keys($params['amount_priceset_level_radio']);
677 }
678 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
679 $totalPrice += $lineItem[$optionValueId]['line_total'];
cde484fd
DL
680 if (
681 $component &&
a6c4ca20
DL
682 // auto_renew exists and is empty in some workflows, which php treat as a 0
683 // and hence we explicity check to see if auto_renew is numeric
cde484fd
DL
684 isset($lineItem[$optionValueId]['auto_renew']) &&
685 is_numeric($lineItem[$optionValueId]['auto_renew'])
686 ) {
6a488035
TO
687 $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
688 }
689 break;
690
691 case 'Select':
692 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
693 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
694 $optionLabel = $field['options'][$optionValueId]['label'];
695 $params['amount_priceset_level_select'] = array();
696 $params['amount_priceset_level_select'][CRM_Utils_Array::key(1, $params["price_{$id}"])] = $optionLabel;
697 if (isset($selectLevel)) {
698 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
699 }
700 else {
701 $selectLevel = array_keys($params['amount_priceset_level_select']);
702 }
703 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
704 $totalPrice += $lineItem[$optionValueId]['line_total'];
cde484fd
DL
705 if (
706 $component &&
707 isset($lineItem[$optionValueId]['auto_renew']) &&
708 is_numeric($lineItem[$optionValueId]['auto_renew'])
709 ) {
6a488035
TO
710 $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
711 }
712 break;
713
714 case 'CheckBox':
715 $params['amount_priceset_level_checkbox'] = $optionIds = array();
716 foreach ($params["price_{$id}"] as $optionId => $option) {
717 $optionIds[] = $optionId;
718 $optionLabel = $field['options'][$optionId]['label'];
719 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
720 if (isset($checkboxLevel)) {
721 $checkboxLevel = array_unique(array_merge(
722 $checkboxLevel,
723 array_keys($params['amount_priceset_level_checkbox'])
724 )
725 );
726 }
727 else {
728 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
729 }
730 }
731 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
732 foreach ($optionIds as $optionId) {
733 $totalPrice += $lineItem[$optionId]['line_total'];
cde484fd
DL
734 if (
735 $component &&
736 isset($lineItem[$optionId]['auto_renew']) &&
737 is_numeric($lineItem[$optionId]['auto_renew'])
738 ) {
6a488035
TO
739 $autoRenew[$lineItem[$optionId]['auto_renew']] += $lineItem[$optionId]['line_total'];
740 }
741 }
742 break;
743 }
744 }
745
746 $amount_level = array();
747 $totalParticipant = 0;
748 if (is_array($lineItem)) {
749 foreach ($lineItem as $values) {
750 $totalParticipant += $values['participant_count'];
751 if ($values['html_type'] == 'Text') {
752 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
753 continue;
754 }
755 $amount_level[] = $values['label'];
756 }
757 }
758
759 $displayParticipantCount = '';
760 if ($totalParticipant > 0) {
761 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
762 }
763 $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
764 $params['amount'] = $totalPrice;
765 if ($component) {
766 foreach ($autoRenew as $dontCare => $eachAmount) {
767 if (!$eachAmount) {
cde484fd 768 unset($autoRenew[$dontCare]);
6a488035
TO
769 }
770 }
771 if (count($autoRenew) > 1 ) {
772 $params['autoRenew'] = $autoRenew;
773 }
774 }
775 }
776
777 /**
778 * Function to build the price set form.
779 *
780 * @return None
781 * @access public
782 */
783 static function buildPriceSet(&$form) {
784 $priceSetId = $form->get('priceSetId');
785 $userid = $form->getVar('_userID');
786 if (!$priceSetId) {
787 return;
788 }
789
790 $validFieldsOnly = TRUE;
791 $className = CRM_Utils_System::getClassName($form);
792 if (in_array($className, array(
793 'CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'))) {
794 $validFieldsOnly = FALSE;
795 }
796
797 $priceSet = self::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
798 $form->_priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
799 $form->_quickConfig = $quickConfig = 0;
800 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $priceSetId, 'is_quick_config')) {
801 $quickConfig = 1;
802 }
803
804 $form->assign('quickConfig', $quickConfig);
805 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
806 $form->_quickConfig = $quickConfig;
807 }
808 $form->assign('priceSet', $form->_priceSet);
809
810 $component = 'contribution';
811 if ($className == 'CRM_Member_Form_Membership') {
812 $component = 'membership';
813 }
814
815 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
816 $feeBlock = &$form->_values['fee'];
817 if (!empty($form->_useForMember)) {
818 $component = 'membership';
819 }
820 }
821 else {
822 $feeBlock = &$form->_priceSet['fields'];
823 }
824
825 // call the hook.
826 CRM_Utils_Hook::buildAmount($component, $form, $feeBlock);
827
828 foreach ($feeBlock as $field) {
829 if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
830 !$validFieldsOnly
831 ) {
832 $options = CRM_Utils_Array::value('options', $field);
833 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
834 $checklifetime = self::checkCurrentMembership($options, $userid);
835 if ($checklifetime) {
836 $form->assign('ispricelifetime', TRUE);
837 }
838 }
839 if (!is_array($options)) {
840 continue;
841 }
842 CRM_Price_BAO_Field::addQuickFormElement($form,
843 'price_' . $field['id'],
844 $field['id'],
845 FALSE,
846 CRM_Utils_Array::value('is_required', $field, FALSE),
847 NULL,
848 $options
849 );
850 }
851 }
852 }
853
854 /**
855 * Function to check the current Membership
856 * having end date null.
857 */
858 static function checkCurrentMembership(&$options, $userid) {
859 if (!$userid || empty($options)) {
860 return;
861 }
862 static $_contact_memberships = array();
863 $checklifetime = FALSE;
864 foreach ($options as $key => $value) {
865 if (CRM_Utils_Array::value('membership_type_id', $value)) {
866 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
867 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership::getContactMembership($userid, $value['membership_type_id'], FALSE);
868 }
869 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
870 if (!empty($currentMembership) && !CRM_Utils_Array::value('end_date', $currentMembership)) {
871 unset($options[$key]);
872 $checklifetime = TRUE;
873 }
874 }
875 }
876 if ($checklifetime) {
877 return TRUE;
878 }
879 else {
880 return FALSE;
881 }
882 }
883
884 /**
885 * Function to set daefult the price set fields.
886 *
887 * @return array $defaults
888 * @access public
889 */
890 static function setDefaultPriceSet(&$form, &$defaults) {
891 if (!isset($form->_priceSet) || empty($form->_priceSet['fields'])) {
892 return $defaults;
893 }
894
895 foreach ($form->_priceSet['fields'] as $key => $val) {
896 foreach ($val['options'] as $keys => $values) {
897 if ($values['is_default']) {
898 if ($val['html_type'] == 'CheckBox') {
899 $defaults["price_{$key}"][$keys] = 1;
900 }
901 else {
902 $defaults["price_{$key}"] = $keys;
903 }
904 }
905 }
906 }
907 return $defaults;
908 }
909
910 /**
911 * Get field ids of a price set
912 *
913 * @param int id Price Set id
914 *
915 * @return array of the field ids
916 *
917 * @access public
918 * @static
919 */
920 public static function getFieldIds($id) {
921 $priceField = new CRM_Price_DAO_Field();
922 $priceField->price_set_id = $id;
923 $priceField->find();
924 while ($priceField->fetch()) {
925 $var[] = $priceField->id;
926 }
927 return $var;
928 }
929
930 /**
931 * This function is to make a copy of a price set, including
932 * all the fields
933 *
934 * @param int $id the price set id to copy
935 *
936 * @return the copy object
937 * @access public
938 * @static
939 */
940 static function copy($id) {
941 $maxId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
942
943 $title = ts('[Copy id %1]', array(1 => $maxId + 1));
944 $fieldsFix = array(
945 'suffix' => array('title' => ' ' . $title,
946 'name' => '__Copy_id_' . ($maxId + 1) . '_',
947 ),
948 );
949
950 $copy = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_Set',
951 array('id' => $id),
952 NULL,
953 $fieldsFix
954 );
955
956 //copying all the blocks pertaining to the price set
957 $copyPriceField = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_Field',
958 array('price_set_id' => $id),
959 array('price_set_id' => $copy->id)
960 );
961 if (!empty($copyPriceField)) {
962 $price = array_combine(self::getFieldIds($id), self::getFieldIds($copy->id));
963
964 //copy option group and values
965 foreach ($price as $originalId => $copyId) {
966 CRM_Core_DAO::copyGeneric('CRM_Price_DAO_FieldValue',
967 array('price_field_id' => $originalId),
968 array('price_field_id' => $copyId)
969 );
970 }
971 }
972 $copy->save();
973
974 CRM_Utils_Hook::copy('Set', $copy);
975 return $copy;
976 }
977
978 /**
979 * This function is to check price set permission
980 *
981 * @param int $sid the price set id
982 */
983 function checkPermission($sid) {
984 if ($sid &&
985 self::eventPriceSetDomainID()
986 ) {
987 $domain_id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $sid, 'domain_id', 'id');
988 if (CRM_Core_Config::domainID() != $domain_id) {
989 CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
990 }
991 }
992 return TRUE;
993 }
994
995 /**
996 * Get the sum of participant count
997 * for all fields of given price set.
998 *
999 * @param int $sid the price set id
1000 *
1001 * @access public
1002 * @static
1003 */
1004 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1005 $count = 0;
1006 if (!$sid) {
1007 return $count;
1008 }
1009
1010 $where = NULL;
1011 if ($onlyActive) {
1012 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1013 }
1014
1015 static $pricesetFieldCount = array();
1016 if (!isset($pricesetFieldCount[$sid])) {
1017 $sql = "
1018 SELECT sum(value.count) as totalCount
1019 FROM civicrm_price_field_value value
1020INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1021INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1022 WHERE pset.id = %1
1023 $where";
1024
1025 $count = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1026 $pricesetFieldCount[$sid] = ($count) ? $count : 0;
1027 }
1028
1029 return $pricesetFieldCount[$sid];
1030 }
1031
1032 public static function getMembershipCount($ids) {
1033 $queryString = "
1034SELECT count( pfv.id ) AS count, pfv.id AS id
1035FROM civicrm_price_field_value pfv
1036INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1037WHERE pfv.id IN ( $ids )
1038GROUP BY mt.member_of_contact_id";
1039
1040 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
1041 $count = array();
1042
1043 while ($crmDAO->fetch()) {
1044 $count[$crmDAO->id] = $crmDAO->count;
1045 }
1046
1047 return $count;
1048 }
1049
1050 /**
1051 * Function to check if auto renew option should be shown
1052 *
1053 * @param int $priceSetId price set id
1054 *
1055 * @return int $autoRenewOption ( 0:hide, 1:optional 2:required )
1056 */
1057 public static function checkAutoRenewForPriceSet($priceSetId) {
1058 // auto-renew option should be visible if membership types associated with all the fields has
1059 // been set for auto-renew option
1060 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1061
1062 // get the membership type auto renew option and check if required or optional
1063 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1064 FROM civicrm_price_field_value pfv
1065 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1066 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1067 WHERE pf.price_set_id = %1
1068 AND pf.is_active = 1
1069 AND pfv.is_active = 1';
1070
1071 $params = array(1 => array($priceSetId, 'Integer'));
1072
1073 $dao = CRM_Core_DAO::executeQuery($query, $params);
1074 $autoRenewOption = 2;
1075 $interval = $unit = array();
1076 while ($dao->fetch()) {
1077 if (!$dao->auto_renew) {
1078 $autoRenewOption = 0;
1079 break;
1080 }
1081 if ($dao->auto_renew == 1) {
1082 $autoRenewOption = 1;
1083 }
1084
1085 $interval[$dao->duration_interval] = $dao->duration_interval;
1086 $unit[$dao->duration_unit] = $dao->duration_unit;
1087 }
1088
1089 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1090 return $autoRenewOption;
1091 }
1092 else {
1093 return 0;
1094 }
1095 }
1096
1097 /**
1098 * Function to retrieve auto renew frequency and interval
1099 *
1100 * @param int $priceSetId price set id
1101 *
1102 * @return array associate array of frequency interval and unit
1103 * @static
1104 * @access public
1105 */
1106 public static function getRecurDetails($priceSetId) {
1107 $query = 'SELECT mt.duration_interval, mt.duration_unit
1108 FROM civicrm_price_field_value pfv
1109 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1110 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1111 WHERE pf.price_set_id = %1 LIMIT 1';
1112
1113 $params = array(1 => array($priceSetId, 'Integer'));
1114 $dao = CRM_Core_DAO::executeQuery($query, $params);
1115 $dao->fetch();
1116 return array($dao->duration_interval, $dao->duration_unit);
1117 }
1118
1119 static function eventPriceSetDomainID() {
1120 return CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME,
1121 'event_price_set_domain_id',
1122 NULL, FALSE
1123 );
1124 }
1125
1126 /**
1127 * update the is_quick_config flag in the db
1128 *
1129 * @param int $id id of the database record
1130 * @param boolean $isQuickConfig value we want to set the is_quick_config field
1131 *
1132 * @return Object DAO object on sucess, null otherwise
1133 * @static
1134 * @access public
1135 */
1136 static function setIsQuickConfig($id, $isQuickConfig) {
1137 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_Set', $id, 'is_quick_config', $isQuickConfig);
1138 }
1139
1140 /**
cde484fd 1141 * Check if price set id provides option for
6a488035
TO
1142 * user to select both auto-renew and non-auto-renew memberships
1143 *
cde484fd 1144 * @access public
6a488035
TO
1145 * @static
1146 *
1147 */
1148 public static function checkMembershipPriceSet($id) {
cde484fd 1149 $query =
6a488035
TO
1150"
1151SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1152FROM civicrm_price_field_value pfv
1153LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1154LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1155LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1156WHERE ps.id = %1
1157";
1158
1159 $params = array(1 => array($id, 'Integer'));
1160 $dao = CRM_Core_DAO::executeQuery($query, $params);
1161
1162 $autoRenew = array();
1163 //FIXME: do a comprehensive check of whether
1164 //2 membership types can be selected
1165 //instead of comparing all of them
1166 while ($dao->fetch()) {
cde484fd 1167 //temp fix for #CRM-10370
6a488035
TO
1168 //if its NULL consider it '0' i.e. 'No auto-renew option'
1169 $daoAutoRenew = $dao->auto_renew;
1170 if ($daoAutoRenew === NULL) {
1171 $daoAutoRenew = 0;
1172 }
1173 if (!empty($autoRenew) && !in_array($daoAutoRenew, $autoRenew)) {
1174 return true;
1175 }
1176 $autoRenew[] = $daoAutoRenew;
1177 }
1178 return false;
1179 }
1180
1181}
1182