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