minor preparatory tidy ups
[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
ffd93213
EM
562 /**
563 * @param $form
564 * @param $id
565 * @param string $entityTable
566 * @param bool $validOnly
567 * @param null $priceSetId
568 *
569 * @return bool|false|int|null
570 */
6a488035
TO
571 static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
572 if (!$priceSetId) {
573 $priceSetId = self::getFor($entityTable, $id);
574 }
575
576 //check if priceset is is_config
577 if (is_numeric($priceSetId)) {
9da8dc8c 578 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
6a488035
TO
579 $form->assign('quickConfig', 1);
580 }
581 }
582 // get price info
583 if ($priceSetId) {
584 if ($form->_action & CRM_Core_Action::UPDATE) {
585 $entityId = $entity = NULL;
586
587 switch ($entityTable) {
588 case 'civicrm_event':
589 $entity = 'participant';
590 if (CRM_Utils_System::getClassName($form) == 'CRM_Event_Form_Participant') {
591 $entityId = $form->_id;
592 }
593 else {
594 $entityId = $form->_participantId;
595 }
596 break;
597
598 case 'civicrm_contribution_page':
599 case 'civicrm_contribution':
600 $entity = 'contribution';
601 $entityId = $form->_id;
602 break;
603 }
604
605 if ($entityId && $entity) {
606 $form->_values['line_items'] = CRM_Price_BAO_LineItem::getLineItems($entityId, $entity);
607 }
608 $required = FALSE;
609 }
610 else {
611 $required = TRUE;
612 }
613
614 $form->_priceSetId = $priceSetId;
615 $priceSet = self::getSetDetail($priceSetId, $required, $validOnly);
616 $form->_priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
617 $form->_values['fee'] = CRM_Utils_Array::value('fields', $form->_priceSet);
618
619 //get the price set fields participant count.
620 if ($entityTable == 'civicrm_event') {
621 //get option count info.
622 $form->_priceSet['optionsCountTotal'] = self::getPricesetCount($priceSetId);
623 if ($form->_priceSet['optionsCountTotal']) {
624 $optionsCountDeails = array();
625 if (!empty($form->_priceSet['fields'])) {
626 foreach ($form->_priceSet['fields'] as $field) {
627 foreach ($field['options'] as $option) {
628 $count = CRM_Utils_Array::value('count', $option, 0);
629 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
630 }
631 }
632 }
633 $form->_priceSet['optionsCountDetails'] = $optionsCountDeails;
634 }
635
636 //get option max value info.
637 $optionsMaxValueTotal = 0;
638 $optionsMaxValueDetails = array();
639
640 if (!empty($form->_priceSet['fields'])) {
641 foreach ($form->_priceSet['fields'] as $field) {
642 foreach ($field['options'] as $option) {
643 $maxVal = CRM_Utils_Array::value('max_value', $option, 0);
644 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
645 $optionsMaxValueTotal += $maxVal;
646 }
647 }
648 }
649
650 $form->_priceSet['optionsMaxValueTotal'] = $optionsMaxValueTotal;
651 if ($optionsMaxValueTotal) {
652 $form->_priceSet['optionsMaxValueDetails'] = $optionsMaxValueDetails;
653 }
654 }
655 $form->set('priceSetId', $form->_priceSetId);
656 $form->set('priceSet', $form->_priceSet);
657
658 return $priceSetId;
659 }
660 return FALSE;
661 }
662
ffd93213
EM
663 /**
664 * @param $fields
665 * @param $params
666 * @param $lineItem
667 * @param string $component
668 */
6a488035
TO
669 static function processAmount(&$fields, &$params, &$lineItem, $component = '') {
670 // using price set
671 $totalPrice = 0;
672 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
673 if ($component) {
674 $autoRenew = array();
675 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
676 }
677 foreach ($fields as $id => $field) {
a7488080 678 if (empty($params["price_{$id}"]) ||
6a488035
TO
679 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
680 ) {
681 // skip if nothing was submitted for this field
682 continue;
683 }
684
685 switch ($field['html_type']) {
686 case 'Text':
687 $params["price_{$id}"] = array(key($field['options']) => $params["price_{$id}"]);
688 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
689 $totalPrice += $lineItem[key($field['options'])]['line_total'];
690 break;
691
692 case 'Radio':
693 //special case if user select -none-
694 if ($params["price_{$id}"] <= 0) {
695 continue;
696 }
697 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
698 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
699 $optionLabel = CRM_Utils_Array::value('label', $field['options'][$optionValueId]);
700 $params['amount_priceset_level_radio'] = array();
701 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
702 if (isset($radioLevel)) {
703 $radioLevel = array_merge($radioLevel,
704 array_keys($params['amount_priceset_level_radio'])
705 );
706 }
707 else {
708 $radioLevel = array_keys($params['amount_priceset_level_radio']);
709 }
710 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
711 $totalPrice += $lineItem[$optionValueId]['line_total'];
cde484fd
DL
712 if (
713 $component &&
a6c4ca20
DL
714 // auto_renew exists and is empty in some workflows, which php treat as a 0
715 // and hence we explicity check to see if auto_renew is numeric
cde484fd
DL
716 isset($lineItem[$optionValueId]['auto_renew']) &&
717 is_numeric($lineItem[$optionValueId]['auto_renew'])
718 ) {
6a488035
TO
719 $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
720 }
721 break;
722
723 case 'Select':
724 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
725 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
726 $optionLabel = $field['options'][$optionValueId]['label'];
727 $params['amount_priceset_level_select'] = array();
728 $params['amount_priceset_level_select'][CRM_Utils_Array::key(1, $params["price_{$id}"])] = $optionLabel;
729 if (isset($selectLevel)) {
730 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
731 }
732 else {
733 $selectLevel = array_keys($params['amount_priceset_level_select']);
734 }
735 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
736 $totalPrice += $lineItem[$optionValueId]['line_total'];
cde484fd
DL
737 if (
738 $component &&
739 isset($lineItem[$optionValueId]['auto_renew']) &&
740 is_numeric($lineItem[$optionValueId]['auto_renew'])
741 ) {
6a488035
TO
742 $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
743 }
744 break;
745
746 case 'CheckBox':
747 $params['amount_priceset_level_checkbox'] = $optionIds = array();
748 foreach ($params["price_{$id}"] as $optionId => $option) {
749 $optionIds[] = $optionId;
750 $optionLabel = $field['options'][$optionId]['label'];
751 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
752 if (isset($checkboxLevel)) {
753 $checkboxLevel = array_unique(array_merge(
754 $checkboxLevel,
755 array_keys($params['amount_priceset_level_checkbox'])
756 )
757 );
758 }
759 else {
760 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
761 }
762 }
763 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
764 foreach ($optionIds as $optionId) {
765 $totalPrice += $lineItem[$optionId]['line_total'];
cde484fd
DL
766 if (
767 $component &&
768 isset($lineItem[$optionId]['auto_renew']) &&
769 is_numeric($lineItem[$optionId]['auto_renew'])
770 ) {
6a488035
TO
771 $autoRenew[$lineItem[$optionId]['auto_renew']] += $lineItem[$optionId]['line_total'];
772 }
773 }
774 break;
775 }
776 }
777
778 $amount_level = array();
779 $totalParticipant = 0;
780 if (is_array($lineItem)) {
781 foreach ($lineItem as $values) {
782 $totalParticipant += $values['participant_count'];
783 if ($values['html_type'] == 'Text') {
784 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
785 continue;
786 }
787 $amount_level[] = $values['label'];
788 }
789 }
790
791 $displayParticipantCount = '';
792 if ($totalParticipant > 0) {
793 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
794 }
795 $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
796 $params['amount'] = $totalPrice;
797 if ($component) {
798 foreach ($autoRenew as $dontCare => $eachAmount) {
799 if (!$eachAmount) {
cde484fd 800 unset($autoRenew[$dontCare]);
6a488035
TO
801 }
802 }
803 if (count($autoRenew) > 1 ) {
804 $params['autoRenew'] = $autoRenew;
805 }
806 }
807 }
808
809 /**
810 * Function to build the price set form.
811 *
dd244018
EM
812 * @param $form
813 *
355ba699 814 * @return void
6a488035
TO
815 * @access public
816 */
817 static function buildPriceSet(&$form) {
818 $priceSetId = $form->get('priceSetId');
819 $userid = $form->getVar('_userID');
820 if (!$priceSetId) {
821 return;
822 }
823
824 $validFieldsOnly = TRUE;
825 $className = CRM_Utils_System::getClassName($form);
826 if (in_array($className, array(
827 'CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'))) {
828 $validFieldsOnly = FALSE;
829 }
830
831 $priceSet = self::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
832 $form->_priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
883e4763 833 $validPriceFieldIds = array_keys($form->_priceSet['fields']);
6a488035 834 $form->_quickConfig = $quickConfig = 0;
9da8dc8c 835 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
6a488035
TO
836 $quickConfig = 1;
837 }
838
839 $form->assign('quickConfig', $quickConfig);
840 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
841 $form->_quickConfig = $quickConfig;
842 }
843 $form->assign('priceSet', $form->_priceSet);
844
845 $component = 'contribution';
846 if ($className == 'CRM_Member_Form_Membership') {
847 $component = 'membership';
848 }
849
850 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
851 $feeBlock = &$form->_values['fee'];
852 if (!empty($form->_useForMember)) {
853 $component = 'membership';
854 }
855 }
856 else {
857 $feeBlock = &$form->_priceSet['fields'];
858 }
859
860 // call the hook.
861 CRM_Utils_Hook::buildAmount($component, $form, $feeBlock);
862
c7b3d063
DG
863 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
864 $adminFieldVisible = false;
865 if (CRM_Core_Permission::check('administer CiviCRM')) {
77b97be7 866 $adminFieldVisible = true;
c7b3d063 867 }
77b97be7 868
883e4763 869 foreach ($feeBlock as $id => $field) {
6a488035 870 if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
c7b3d063 871 (CRM_Utils_Array::value('visibility', $field) == 'admin' && $adminFieldVisible == true) ||
6a488035
TO
872 !$validFieldsOnly
873 ) {
874 $options = CRM_Utils_Array::value('options', $field);
875 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
876 $checklifetime = self::checkCurrentMembership($options, $userid);
877 if ($checklifetime) {
878 $form->assign('ispricelifetime', TRUE);
879 }
880 }
883e4763 881 if (!is_array($options) || !in_array($id, $validPriceFieldIds)) {
6a488035
TO
882 continue;
883 }
9da8dc8c 884 CRM_Price_BAO_PriceField::addQuickFormElement($form,
6a488035
TO
885 'price_' . $field['id'],
886 $field['id'],
887 FALSE,
888 CRM_Utils_Array::value('is_required', $field, FALSE),
889 NULL,
890 $options
891 );
892 }
893 }
894 }
895
896 /**
897 * Function to check the current Membership
898 * having end date null.
899 */
900 static function checkCurrentMembership(&$options, $userid) {
901 if (!$userid || empty($options)) {
902 return;
903 }
904 static $_contact_memberships = array();
905 $checklifetime = FALSE;
906 foreach ($options as $key => $value) {
a7488080 907 if (!empty($value['membership_type_id'])) {
6a488035
TO
908 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
909 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership::getContactMembership($userid, $value['membership_type_id'], FALSE);
910 }
911 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
8cc574cf 912 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
6a488035
TO
913 unset($options[$key]);
914 $checklifetime = TRUE;
915 }
916 }
917 }
918 if ($checklifetime) {
919 return TRUE;
920 }
921 else {
922 return FALSE;
923 }
924 }
925
926 /**
927 * Function to set daefult the price set fields.
928 *
fd31fa4c
EM
929 * @param $form
930 * @param $defaults
931 *
6a488035
TO
932 * @return array $defaults
933 * @access public
934 */
935 static function setDefaultPriceSet(&$form, &$defaults) {
936 if (!isset($form->_priceSet) || empty($form->_priceSet['fields'])) {
937 return $defaults;
938 }
939
940 foreach ($form->_priceSet['fields'] as $key => $val) {
941 foreach ($val['options'] as $keys => $values) {
942 if ($values['is_default']) {
943 if ($val['html_type'] == 'CheckBox') {
944 $defaults["price_{$key}"][$keys] = 1;
945 }
946 else {
947 $defaults["price_{$key}"] = $keys;
948 }
949 }
950 }
951 }
952 return $defaults;
953 }
954
955 /**
956 * Get field ids of a price set
957 *
958 * @param int id Price Set id
959 *
960 * @return array of the field ids
961 *
962 * @access public
963 * @static
964 */
965 public static function getFieldIds($id) {
9da8dc8c 966 $priceField = new CRM_Price_DAO_PriceField();
6a488035
TO
967 $priceField->price_set_id = $id;
968 $priceField->find();
969 while ($priceField->fetch()) {
970 $var[] = $priceField->id;
971 }
972 return $var;
973 }
974
975 /**
976 * This function is to make a copy of a price set, including
977 * all the fields
978 *
979 * @param int $id the price set id to copy
980 *
981 * @return the copy object
982 * @access public
983 * @static
984 */
985 static function copy($id) {
986 $maxId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
987
988 $title = ts('[Copy id %1]', array(1 => $maxId + 1));
989 $fieldsFix = array(
990 'suffix' => array('title' => ' ' . $title,
991 'name' => '__Copy_id_' . ($maxId + 1) . '_',
992 ),
993 );
994
9da8dc8c 995 $copy = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSet',
6a488035
TO
996 array('id' => $id),
997 NULL,
998 $fieldsFix
999 );
1000
1001 //copying all the blocks pertaining to the price set
9da8dc8c 1002 $copyPriceField = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceField',
6a488035
TO
1003 array('price_set_id' => $id),
1004 array('price_set_id' => $copy->id)
1005 );
1006 if (!empty($copyPriceField)) {
1007 $price = array_combine(self::getFieldIds($id), self::getFieldIds($copy->id));
1008
1009 //copy option group and values
1010 foreach ($price as $originalId => $copyId) {
9da8dc8c 1011 CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceFieldValue',
6a488035
TO
1012 array('price_field_id' => $originalId),
1013 array('price_field_id' => $copyId)
1014 );
1015 }
1016 }
1017 $copy->save();
1018
1019 CRM_Utils_Hook::copy('Set', $copy);
1020 return $copy;
1021 }
1022
1023 /**
1024 * This function is to check price set permission
1025 *
1026 * @param int $sid the price set id
77b97be7
EM
1027 *
1028 * @return bool
6a488035 1029 */
44c8822b
DL
1030 static function checkPermission($sid) {
1031 if ($sid && self::eventPriceSetDomainID()) {
9da8dc8c 1032 $domain_id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
6a488035
TO
1033 if (CRM_Core_Config::domainID() != $domain_id) {
1034 CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
1035 }
1036 }
1037 return TRUE;
1038 }
1039
1040 /**
1041 * Get the sum of participant count
1042 * for all fields of given price set.
1043 *
1044 * @param int $sid the price set id
1045 *
77b97be7
EM
1046 * @param bool $onlyActive
1047 *
1048 * @return int|null|string
6a488035
TO
1049 * @access public
1050 * @static
1051 */
1052 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1053 $count = 0;
1054 if (!$sid) {
1055 return $count;
1056 }
1057
1058 $where = NULL;
1059 if ($onlyActive) {
1060 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1061 }
1062
1063 static $pricesetFieldCount = array();
1064 if (!isset($pricesetFieldCount[$sid])) {
1065 $sql = "
1066 SELECT sum(value.count) as totalCount
1067 FROM civicrm_price_field_value value
1068INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1069INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1070 WHERE pset.id = %1
1071 $where";
1072
1073 $count = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1074 $pricesetFieldCount[$sid] = ($count) ? $count : 0;
1075 }
1076
1077 return $pricesetFieldCount[$sid];
1078 }
1079
ffd93213
EM
1080 /**
1081 * @param $ids
1082 *
1083 * @return array
1084 */
6a488035
TO
1085 public static function getMembershipCount($ids) {
1086 $queryString = "
1087SELECT count( pfv.id ) AS count, pfv.id AS id
1088FROM civicrm_price_field_value pfv
1089INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1090WHERE pfv.id IN ( $ids )
1091GROUP BY mt.member_of_contact_id";
1092
1093 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
1094 $count = array();
1095
1096 while ($crmDAO->fetch()) {
1097 $count[$crmDAO->id] = $crmDAO->count;
1098 }
1099
1100 return $count;
1101 }
1102
1103 /**
1104 * Function to check if auto renew option should be shown
1105 *
1106 * @param int $priceSetId price set id
1107 *
1108 * @return int $autoRenewOption ( 0:hide, 1:optional 2:required )
1109 */
1110 public static function checkAutoRenewForPriceSet($priceSetId) {
1111 // auto-renew option should be visible if membership types associated with all the fields has
1112 // been set for auto-renew option
1113 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1114
1115 // get the membership type auto renew option and check if required or optional
1116 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1117 FROM civicrm_price_field_value pfv
1118 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1119 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1120 WHERE pf.price_set_id = %1
1121 AND pf.is_active = 1
1122 AND pfv.is_active = 1';
1123
1124 $params = array(1 => array($priceSetId, 'Integer'));
1125
1126 $dao = CRM_Core_DAO::executeQuery($query, $params);
1127 $autoRenewOption = 2;
1128 $interval = $unit = array();
1129 while ($dao->fetch()) {
1130 if (!$dao->auto_renew) {
1131 $autoRenewOption = 0;
1132 break;
1133 }
1134 if ($dao->auto_renew == 1) {
1135 $autoRenewOption = 1;
1136 }
1137
1138 $interval[$dao->duration_interval] = $dao->duration_interval;
1139 $unit[$dao->duration_unit] = $dao->duration_unit;
1140 }
1141
1142 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1143 return $autoRenewOption;
1144 }
1145 else {
1146 return 0;
1147 }
1148 }
1149
1150 /**
1151 * Function to retrieve auto renew frequency and interval
1152 *
1153 * @param int $priceSetId price set id
1154 *
1155 * @return array associate array of frequency interval and unit
1156 * @static
1157 * @access public
1158 */
1159 public static function getRecurDetails($priceSetId) {
1160 $query = 'SELECT mt.duration_interval, mt.duration_unit
1161 FROM civicrm_price_field_value pfv
1162 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1163 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1164 WHERE pf.price_set_id = %1 LIMIT 1';
1165
1166 $params = array(1 => array($priceSetId, 'Integer'));
1167 $dao = CRM_Core_DAO::executeQuery($query, $params);
1168 $dao->fetch();
1169 return array($dao->duration_interval, $dao->duration_unit);
1170 }
1171
ffd93213
EM
1172 /**
1173 * @return object
1174 */
6a488035
TO
1175 static function eventPriceSetDomainID() {
1176 return CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME,
1177 'event_price_set_domain_id',
1178 NULL, FALSE
1179 );
1180 }
1181
1182 /**
1183 * update the is_quick_config flag in the db
1184 *
1185 * @param int $id id of the database record
1186 * @param boolean $isQuickConfig value we want to set the is_quick_config field
1187 *
1188 * @return Object DAO object on sucess, null otherwise
1189 * @static
1190 * @access public
1191 */
1192 static function setIsQuickConfig($id, $isQuickConfig) {
9da8dc8c 1193 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
6a488035
TO
1194 }
1195
1196 /**
cde484fd 1197 * Check if price set id provides option for
6a488035
TO
1198 * user to select both auto-renew and non-auto-renew memberships
1199 *
cde484fd 1200 * @access public
6a488035
TO
1201 * @static
1202 *
1203 */
1204 public static function checkMembershipPriceSet($id) {
cde484fd 1205 $query =
6a488035
TO
1206"
1207SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1208FROM civicrm_price_field_value pfv
1209LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1210LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1211LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1212WHERE ps.id = %1
1213";
1214
1215 $params = array(1 => array($id, 'Integer'));
1216 $dao = CRM_Core_DAO::executeQuery($query, $params);
1217
1218 $autoRenew = array();
1219 //FIXME: do a comprehensive check of whether
1220 //2 membership types can be selected
1221 //instead of comparing all of them
1222 while ($dao->fetch()) {
cde484fd 1223 //temp fix for #CRM-10370
6a488035
TO
1224 //if its NULL consider it '0' i.e. 'No auto-renew option'
1225 $daoAutoRenew = $dao->auto_renew;
1226 if ($daoAutoRenew === NULL) {
1227 $daoAutoRenew = 0;
1228 }
1229 if (!empty($autoRenew) && !in_array($daoAutoRenew, $autoRenew)) {
1230 return true;
1231 }
1232 $autoRenew[] = $daoAutoRenew;
1233 }
1234 return false;
1235 }
1236
c6914066
PN
1237 /*
1238 * Copy priceSet when event/contibution page is copied
1239 *
1240 * @params string $baoName BAO name
1241 * @params int $id old event/contribution page id
1242 * @params int $newId newly created event/contribution page id
1243 *
1244 */
ffd93213
EM
1245 /**
1246 * @param $baoName
1247 * @param $id
1248 * @param $newId
1249 */
c6914066 1250 static function copyPriceSet($baoName, $id, $newId) {
9da8dc8c 1251 $priceSetId = CRM_Price_BAO_PriceSet::getFor($baoName, $id);
c6914066 1252 if ($priceSetId) {
9da8dc8c 1253 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
c6914066 1254 if($isQuickConfig) {
9da8dc8c 1255 $copyPriceSet = &CRM_Price_BAO_PriceSet::copy($priceSetId);
1256 CRM_Price_BAO_PriceSet::addTo($baoName, $newId, $copyPriceSet->id);
44c8822b 1257 }
c6914066 1258 else {
9da8dc8c 1259 $copyPriceSet = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSetEntity',
c6914066
PN
1260 array(
1261 'entity_id' => $id,
1262 'entity_table' => $baoName,
1263 ),
1264 array('entity_id' => $newId)
1265 );
1266 }
1267 // copy event discount
1268 if ($baoName == 'civicrm_event') {
1269 $discount = CRM_Core_BAO_Discount::getOptionGroup($id, 'civicrm_event');
1270 foreach ($discount as $discountId => $setId) {
1271
9da8dc8c 1272 $copyPriceSet = &CRM_Price_BAO_PriceSet::copy($setId);
44c8822b 1273
c6914066
PN
1274 $copyDiscount = &CRM_Core_DAO::copyGeneric(
1275 'CRM_Core_DAO_Discount',
1276 array(
1277 'id' => $discountId,
1278 ),
1279 array(
1280 'entity_id' => $newId,
1281 'price_set_id' => $copyPriceSet->id,
1282 )
1283 );
1284 }
1285 }
1286 }
1287 }
6a488035
TO
1288}
1289