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