Merge pull request #7836 from eileenmcnaughton/master
[civicrm-core.git] / CRM / Price / BAO / PriceSet.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 +--------------------------------------------------------------------+
e70a7fc0 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
e7112fa7 31 * @copyright CiviCRM LLC (c) 2004-2015
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 41
71ba92c4 42 /**
fe482240 43 * Static field for default price set details.
71ba92c4
PN
44 *
45 * @var array
71ba92c4
PN
46 */
47 static $_defaultPriceSet = NULL;
48
6a488035 49 /**
fe482240 50 * Class constructor.
6a488035 51 */
00be9182 52 public function __construct() {
6a488035
TO
53 parent::__construct();
54 }
55
56 /**
fe482240 57 * Takes an associative array and creates a price set object.
6a488035 58 *
414c1420
TO
59 * @param array $params
60 * (reference) an assoc array of name/value pairs.
6a488035 61 *
16b10e64 62 * @return CRM_Price_DAO_PriceSet
6a488035 63 */
00be9182 64 public static function create(&$params) {
22e263ad 65 if (empty($params['id']) && empty($params['name'])) {
e0c1764e
EM
66 $params['name'] = CRM_Utils_String::munge($params['title'], '_', 242);
67 }
e10ac060 68 if (!empty($params['extends']) && is_array($params['extends'])) {
076809e3
JV
69 $params['extends'] = CRM_Utils_Array::implodePadded($params['extends']);
70 }
9da8dc8c 71 $priceSetBAO = new CRM_Price_BAO_PriceSet();
6a488035
TO
72 $priceSetBAO->copyValues($params);
73 if (self::eventPriceSetDomainID()) {
74 $priceSetBAO->domain_id = CRM_Core_Config::domainID();
75 }
76 return $priceSetBAO->save();
77 }
78
79 /**
fe482240 80 * Fetch object based on array of properties.
6a488035 81 *
414c1420
TO
82 * @param array $params
83 * (reference ) an assoc array of name/value pairs.
84 * @param array $defaults
85 * (reference ) an assoc array to hold the flattened values.
6a488035 86 *
16b10e64 87 * @return CRM_Price_DAO_PriceSet
6a488035 88 */
00be9182 89 public static function retrieve(&$params, &$defaults) {
9da8dc8c 90 return CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
6a488035
TO
91 }
92
93 /**
fe482240 94 * Update the is_active flag in the db.
6a488035 95 *
414c1420
TO
96 * @param int $id
97 * Id of the database record.
6c8f6e67
EM
98 * @param $isActive
99 *
100 * @internal param bool $is_active value we want to set the is_active field
6a488035 101 *
a6c01b45 102 * @return Object
b44e3f84 103 * DAO object on success, null otherwise
6a488035 104 */
00be9182 105 public static function setIsActive($id, $isActive) {
9da8dc8c 106 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
6a488035
TO
107 }
108
109 /**
110 * Calculate the default price set id
111 * assigned to the contribution/membership etc
112 *
113 * @param string $entity
114 *
a6c01b45
CW
115 * @return array
116 * default price set
6a488035 117 *
6a488035
TO
118 */
119 public static function getDefaultPriceSet($entity = 'contribution') {
71ba92c4
PN
120 if (!empty(self::$_defaultPriceSet[$entity])) {
121 return self::$_defaultPriceSet[$entity];
122 }
e0c1764e
EM
123 $entityName = 'default_contribution_amount';
124 if ($entity == 'membership') {
6a488035
TO
125 $entityName = 'default_membership_type_amount';
126 }
127
128 $sql = "
82cc6775 129SELECT ps.id AS setID, pfv.price_field_id AS priceFieldID, pfv.id AS priceFieldValueID, pfv.name, pfv.label, pfv.membership_type_id, pfv.amount, pfv.financial_type_id
6a488035
TO
130FROM civicrm_price_set ps
131LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
132LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
133WHERE ps.name = '{$entityName}'
134";
135
136 $dao = CRM_Core_DAO::executeQuery($sql);
71ba92c4 137 self::$_defaultPriceSet[$entity] = array();
6a488035 138 while ($dao->fetch()) {
71ba92c4 139 self::$_defaultPriceSet[$entity][$dao->priceFieldValueID] = array(
353ffa53
TO
140 'setID' => $dao->setID,
141 'priceFieldID' => $dao->priceFieldID,
142 'name' => $dao->name,
143 'label' => $dao->label,
144 'priceFieldValueID' => $dao->priceFieldValueID,
145 'membership_type_id' => $dao->membership_type_id,
146 'amount' => $dao->amount,
147 'financial_type_id' => $dao->financial_type_id,
71ba92c4 148 );
6a488035
TO
149 }
150
71ba92c4 151 return self::$_defaultPriceSet[$entity];
6a488035
TO
152 }
153
154 /**
155 * Get the price set title.
156 *
414c1420
TO
157 * @param int $id
158 * Id of price set.
6a488035 159 *
a6c01b45
CW
160 * @return string
161 * title
6a488035 162 *
6a488035
TO
163 */
164 public static function getTitle($id) {
9da8dc8c 165 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
6a488035
TO
166 }
167
168 /**
169 * Return a list of all forms which use this price set.
170 *
414c1420
TO
171 * @param int $id
172 * Id of price set.
e0c1764e 173 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
6a488035
TO
174 *
175 * @return array
176 */
177 public static function &getUsedBy($id, $simpleReturn = FALSE) {
178 $usedBy = $forms = $tables = array();
179 $queryString = "
180SELECT entity_table, entity_id
181FROM civicrm_price_set_entity
182WHERE price_set_id = %1";
183 $params = array(1 => array($id, 'Integer'));
184 $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
185
186 while ($crmFormDAO->fetch()) {
187 $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
188 $tables[] = $crmFormDAO->entity_table;
189 }
190 // Return only tables
191 if ($simpleReturn == 'table') {
192 return $tables;
193 }
194 if (empty($forms)) {
195 $queryString = "
196SELECT cli.entity_table, cli.entity_id
197FROM civicrm_line_item cli
198LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
199WHERE cpf.price_set_id = %1";
200 $params = array(1 => array($id, 'Integer'));
201 $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
202 while ($crmFormDAO->fetch()) {
203 $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
204 $tables[] = $crmFormDAO->entity_table;
205 }
206 if (empty($forms)) {
207 return $usedBy;
208 }
209 }
210 // Return only entity data
211 if ($simpleReturn == 'entity') {
212 return $forms;
213 }
214 foreach ($forms as $table => $entities) {
215 switch ($table) {
216 case 'civicrm_event':
217 $ids = implode(',', $entities);
c34e4bb4 218 $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
219FROM civicrm_event ce
220LEFT JOIN civicrm_option_value ON
221 ( ce.event_type_id = civicrm_option_value.value )
222LEFT JOIN civicrm_option_group ON
223 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
224WHERE
225 civicrm_option_group.name = 'event_type' AND
6a488035
TO
226 ce.id IN ($ids) AND
227 ce.is_active = 1;";
228 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
229 while ($crmDAO->fetch()) {
c34e4bb4
PJ
230 if ($crmDAO->isTemplate) {
231 $usedBy['civicrm_event_template'][$crmDAO->id]['title'] = $crmDAO->templateTitle;
232 $usedBy['civicrm_event_template'][$crmDAO->id]['eventType'] = $crmDAO->eventType;
233 $usedBy['civicrm_event_template'][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
234 }
235 else {
236 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
237 $usedBy[$table][$crmDAO->id]['eventType'] = $crmDAO->eventType;
238 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
239 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
240 $usedBy[$table][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
241 }
6a488035
TO
242 }
243 break;
244
245 case 'civicrm_contribution_page':
246 $ids = implode(',', $entities);
247 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
248FROM civicrm_contribution_page cp, civicrm_financial_type ct
cde484fd 249WHERE ct.id = cp.financial_type_id AND
6a488035
TO
250 cp.id IN ($ids) AND
251 cp.is_active = 1;";
252 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
253 while ($crmDAO->fetch()) {
254 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
255 $usedBy[$table][$crmDAO->id]['type'] = $crmDAO->type;
256 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
257 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
258 }
259 break;
260
261 case 'civicrm_contribution':
262 case 'civicrm_membership':
263 case 'civicrm_participant':
264 $usedBy[$table] = 1;
265 break;
266
267 default:
268 CRM_Core_Error::fatal("$table is not supported in PriceSet::usedBy()");
269 break;
270 }
271 }
272
273 return $usedBy;
274 }
275
276 /**
fe482240 277 * Delete the price set.
6a488035 278 *
414c1420
TO
279 * @param int $id
280 * Price Set id.
6a488035 281 *
acb1052e 282 * @return bool
a6c01b45 283 * false if fields exist for this set, true if the
16b10e64 284 * set could be deleted
6a488035 285 *
6a488035
TO
286 */
287 public static function deleteSet($id) {
288 // remove from all inactive forms
289 $usedBy = self::getUsedBy($id);
290 if (isset($usedBy['civicrm_event'])) {
291 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
292 $eventDAO = new CRM_Event_DAO_Event();
293 $eventDAO->id = $eventId;
294 $eventDAO->find();
295 while ($eventDAO->fetch()) {
296 self::removeFrom('civicrm_event', $eventDAO->id);
297 }
298 }
299 }
300
301 // delete price fields
9da8dc8c 302 $priceField = new CRM_Price_DAO_PriceField();
6a488035
TO
303 $priceField->price_set_id = $id;
304 $priceField->find();
305 while ($priceField->fetch()) {
306 // delete options first
9da8dc8c 307 CRM_Price_BAO_PriceField::deleteField($priceField->id);
6a488035
TO
308 }
309
9da8dc8c 310 $set = new CRM_Price_DAO_PriceSet();
6a488035
TO
311 $set->id = $id;
312 return $set->delete();
313 }
314
315 /**
fe482240 316 * Link the price set with the specified table and id.
6a488035
TO
317 *
318 * @param string $entityTable
414c1420
TO
319 * @param int $entityId
320 * @param int $priceSetId
6a488035
TO
321 *
322 * @return bool
323 */
324 public static function addTo($entityTable, $entityId, $priceSetId) {
325 // verify that the price set exists
9da8dc8c 326 $dao = new CRM_Price_DAO_PriceSet();
6a488035
TO
327 $dao->id = $priceSetId;
328 if (!$dao->find()) {
329 return FALSE;
330 }
331 unset($dao);
332
9da8dc8c 333 $dao = new CRM_Price_DAO_PriceSetEntity();
6a488035
TO
334 // find if this already exists
335 $dao->entity_id = $entityId;
336 $dao->entity_table = $entityTable;
337 $dao->find(TRUE);
338
339 // add or update price_set_id
340 $dao->price_set_id = $priceSetId;
341 return $dao->save();
342 }
343
344 /**
fe482240 345 * Delete price set for the given entity and id.
6a488035
TO
346 *
347 * @param string $entityTable
414c1420 348 * @param int $entityId
77b97be7
EM
349 *
350 * @return mixed
6a488035
TO
351 */
352 public static function removeFrom($entityTable, $entityId) {
353ffa53 353 $dao = new CRM_Price_DAO_PriceSetEntity();
6a488035 354 $dao->entity_table = $entityTable;
353ffa53 355 $dao->entity_id = $entityId;
6a488035
TO
356 return $dao->delete();
357 }
358
359 /**
360 * Find a price_set_id associatied with the given table, id and usedFor
361 * Used For value for events:1, contribution:2, membership:3
362 *
363 * @param string $entityTable
77b97be7 364 * @param int $entityId
414c1420
TO
365 * @param int $usedFor
366 * ( price set that extends/used for particular component ).
77b97be7
EM
367 *
368 * @param null $isQuickConfig
369 * @param null $setName
6a488035 370 *
df8d3074 371 * @return int|false
72b3a70c 372 * price_set_id, or false if none found
6a488035
TO
373 */
374 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
375 if (!$entityTable || !$entityId) {
376 return FALSE;
377 }
378
379 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
380 FROM civicrm_price_set ps
381 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
382 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
383 if ($isQuickConfig) {
384 $sql .= ' AND ps.is_quick_config = 0 ';
385 }
ba1dcfda 386 $params = array(
353ffa53
TO
387 1 => array($entityTable, 'String'),
388 2 => array($entityId, 'Integer'),
6a488035
TO
389 );
390 if ($usedFor) {
391 $sql .= " AND ps.extends LIKE '%%3%' ";
392 $params[3] = array($usedFor, 'Integer');
393 }
394
395 $dao = CRM_Core_DAO::executeQuery($sql, $params);
396 $dao->fetch();
397 $setName = (isset($dao->price_set_name)) ? $dao->price_set_name : FALSE;
398 return (isset($dao->price_set_id)) ? $dao->price_set_id : FALSE;
399 }
400
401 /**
fe482240 402 * Find a price_set_id associated with the given option value or field ID.
6a488035 403 *
414c1420
TO
404 * @param array $params
405 * (reference) an assoc array of name/value pairs.
6a488035
TO
406 * array may contain either option id or
407 * price field id
408 *
df8d3074 409 * @return int|NULL
72b3a70c 410 * price set id on success, null otherwise
6a488035
TO
411 */
412 public static function getSetId(&$params) {
413 $fid = NULL;
414
415 if ($oid = CRM_Utils_Array::value('oid', $params)) {
9da8dc8c 416 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
6a488035
TO
417 $fieldValue->id = $oid;
418 if ($fieldValue->find(TRUE)) {
419 $fid = $fieldValue->price_field_id;
420 }
421 }
422 else {
423 $fid = CRM_Utils_Array::value('fid', $params);
424 }
425
426 if (isset($fid)) {
9da8dc8c 427 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
6a488035
TO
428 }
429
430 return NULL;
431 }
432
433 /**
fe482240 434 * Return an associative array of all price sets.
6a488035 435 *
414c1420
TO
436 * @param bool $withInactive
437 * Whether or not to include inactive entries.
77b97be7 438 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
6a3d8d2d 439 * @param string $column name of the column.
6a488035 440 *
a6c01b45
CW
441 * @return array
442 * associative array of id => name
6a488035 443 */
6a3d8d2d
WA
444 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE, $column = 'title') {
445 $query = "
6a488035 446 SELECT
75d6d479 447 DISTINCT ( price_set_id ) as id, s.{$column}
6a488035 448 FROM
53df1142
E
449 civicrm_price_set s
450 INNER JOIN civicrm_price_field f ON f.price_set_id = s.id
451 INNER JOIN civicrm_price_field_value v ON v.price_field_id = f.id
6a488035 452 WHERE
75d6d479 453 is_quick_config = 0 ";
6a488035
TO
454
455 if (!$withInactive) {
53df1142 456 $query .= ' AND s.is_active = 1 ';
6a488035
TO
457 }
458
459 if (self::eventPriceSetDomainID()) {
53df1142 460 $query .= ' AND s.domain_id = ' . CRM_Core_Config::domainID();
6a488035
TO
461 }
462
463 $priceSets = array();
464
465 if ($extendComponentName) {
466 $componentId = CRM_Core_Component::getComponentID($extendComponentName);
467 if (!$componentId) {
468 return $priceSets;
469 }
53df1142 470 $query .= " AND s.extends LIKE '%$componentId%' ";
6a488035 471 }
53df1142 472 // Check permissioned financial types
573fd305 473 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialType, CRM_Core_Action::ADD);
53df1142 474 if ($financialType) {
40c655aa 475 $types = implode(',', array_keys($financialType));
53df1142
E
476 $query .= ' AND s.financial_type_id IN (' . $types . ') AND v.financial_type_id IN (' . $types . ') ';
477 }
478 else {
c5c263ca
AH
479 // Do not display any price sets
480 $query .= " AND 0 ";
53df1142
E
481 }
482 $query .= " GROUP BY s.id";
6a488035
TO
483 $dao = CRM_Core_DAO::executeQuery($query);
484 while ($dao->fetch()) {
6a3d8d2d 485 $priceSets[$dao->id] = $dao->$column;
6a488035
TO
486 }
487 return $priceSets;
488 }
489
490 /**
fe482240 491 * Get price set details.
6a488035
TO
492 *
493 * An array containing price set details (including price fields) is returned
494 *
100fef9d 495 * @param int $setID
003ca729 496 * Price Set ID.
2a6da8d7 497 * @param bool $required
003ca729 498 * Appears to have no effect based on reading the code.
2a6da8d7 499 * @param bool $validOnly
003ca729 500 * Should only fields where today's date falls within the valid range be returned?
2a6da8d7 501 *
a6c01b45 502 * @return array
003ca729 503 * Array consisting of field details
6a488035
TO
504 */
505 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
506 // create a new tree
507 $setTree = array();
6a488035
TO
508
509 $priceFields = array(
510 'id',
511 'name',
512 'label',
513 'html_type',
514 'is_enter_qty',
515 'help_pre',
516 'help_post',
517 'weight',
518 'is_display_amounts',
519 'options_per_line',
520 'is_active',
521 'active_on',
522 'expire_on',
523 'javascript',
524 'visibility_id',
525 'is_required',
526 );
527 if ($required == TRUE) {
528 $priceFields[] = 'is_required';
529 }
530
531 // create select
532 $select = 'SELECT ' . implode(',', $priceFields);
533 $from = ' FROM civicrm_price_field';
534
353ffa53 535 $params = array();
6a488035 536 $params[1] = array($setID, 'Integer');
353ffa53 537 $where = '
6a488035
TO
538WHERE price_set_id = %1
539AND is_active = 1
540';
541 $dateSelect = '';
542 if ($validOnly) {
543 $currentTime = date('YmdHis');
544 $dateSelect = "
545AND ( active_on IS NULL OR active_on <= {$currentTime} )
546AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
547";
548 }
549
550 $orderBy = ' ORDER BY weight';
551
552 $sql = $select . $from . $where . $dateSelect . $orderBy;
553
554 $dao = CRM_Core_DAO::executeQuery($sql, $params);
555
556 $visibility = CRM_Core_PseudoConstant::visibility('name');
557 while ($dao->fetch()) {
558 $fieldID = $dao->id;
559
560 $setTree[$setID]['fields'][$fieldID] = array();
561 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
562
563 foreach ($priceFields as $field) {
564 if ($field == 'id' || is_null($dao->$field)) {
565 continue;
566 }
567
568 if ($field == 'visibility_id') {
569 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
570 }
571 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
572 }
9da8dc8c 573 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField::getOptions($fieldID, FALSE);
6a488035
TO
574 }
575
576 // also get the pre and post help from this price set
577 $sql = "
578SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
579FROM civicrm_price_set
580WHERE id = %1";
581 $dao = CRM_Core_DAO::executeQuery($sql, $params);
582 if ($dao->fetch()) {
583 $setTree[$setID]['extends'] = $dao->extends;
157b21d8 584 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id;
6a488035
TO
585 $setTree[$setID]['help_pre'] = $dao->help_pre;
586 $setTree[$setID]['help_post'] = $dao->help_post;
587 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config;
588 }
589 return $setTree;
590 }
591
85020e43 592 /**
003ca729
EM
593 * Get the Price Field ID.
594 *
595 * We call this function when more than one being present would represent an error
85020e43
EM
596 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
597 * @param array $priceSet
598 *
599 * @throws CRM_Core_Exception
600 * @return int
601 */
00be9182 602 public static function getOnlyPriceFieldID(array $priceSet) {
22e263ad 603 if (count($priceSet['fields']) > 1) {
85020e43
EM
604 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
605 }
606 return (int) implode('_', array_keys($priceSet['fields']));
607 }
608
609 /**
610 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
611 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
612 * @param array $priceSet
613 *
614 * @throws CRM_Core_Exception
615 * @return int
616 */
00be9182 617 public static function getOnlyPriceFieldValueID(array $priceSet) {
85020e43 618 $priceFieldID = self::getOnlyPriceFieldID($priceSet);
22e263ad 619 if (count($priceSet['fields'][$priceFieldID]['options']) > 1) {
85020e43
EM
620 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
621 }
622 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
623 }
624
625
ffd93213 626 /**
003ca729
EM
627 * Initiate price set such that various non-BAO things are set on the form.
628 *
629 * This function is not really a BAO function so the location is misleading.
630 *
e0c1764e 631 * @param CRM_Core_Form $form
100fef9d 632 * @param int $id
003ca729 633 * Form entity id.
ffd93213
EM
634 * @param string $entityTable
635 * @param bool $validOnly
100fef9d 636 * @param int $priceSetId
003ca729 637 * Price Set ID
ffd93213
EM
638 *
639 * @return bool|false|int|null
640 */
00be9182 641 public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
6a488035
TO
642 if (!$priceSetId) {
643 $priceSetId = self::getFor($entityTable, $id);
644 }
645
646 //check if priceset is is_config
647 if (is_numeric($priceSetId)) {
9da8dc8c 648 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
6a488035
TO
649 $form->assign('quickConfig', 1);
650 }
651 }
652 // get price info
653 if ($priceSetId) {
654 if ($form->_action & CRM_Core_Action::UPDATE) {
655 $entityId = $entity = NULL;
656
657 switch ($entityTable) {
658 case 'civicrm_event':
659 $entity = 'participant';
660 if (CRM_Utils_System::getClassName($form) == 'CRM_Event_Form_Participant') {
661 $entityId = $form->_id;
662 }
663 else {
664 $entityId = $form->_participantId;
665 }
666 break;
667
668 case 'civicrm_contribution_page':
669 case 'civicrm_contribution':
670 $entity = 'contribution';
671 $entityId = $form->_id;
672 break;
673 }
674
675 if ($entityId && $entity) {
676 $form->_values['line_items'] = CRM_Price_BAO_LineItem::getLineItems($entityId, $entity);
677 }
678 $required = FALSE;
679 }
680 else {
681 $required = TRUE;
682 }
683
684 $form->_priceSetId = $priceSetId;
685 $priceSet = self::getSetDetail($priceSetId, $required, $validOnly);
686 $form->_priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
687 $form->_values['fee'] = CRM_Utils_Array::value('fields', $form->_priceSet);
688
689 //get the price set fields participant count.
690 if ($entityTable == 'civicrm_event') {
691 //get option count info.
692 $form->_priceSet['optionsCountTotal'] = self::getPricesetCount($priceSetId);
693 if ($form->_priceSet['optionsCountTotal']) {
694 $optionsCountDeails = array();
695 if (!empty($form->_priceSet['fields'])) {
696 foreach ($form->_priceSet['fields'] as $field) {
697 foreach ($field['options'] as $option) {
698 $count = CRM_Utils_Array::value('count', $option, 0);
699 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
700 }
701 }
702 }
703 $form->_priceSet['optionsCountDetails'] = $optionsCountDeails;
704 }
705
706 //get option max value info.
707 $optionsMaxValueTotal = 0;
708 $optionsMaxValueDetails = array();
709
710 if (!empty($form->_priceSet['fields'])) {
711 foreach ($form->_priceSet['fields'] as $field) {
712 foreach ($field['options'] as $option) {
713 $maxVal = CRM_Utils_Array::value('max_value', $option, 0);
714 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
715 $optionsMaxValueTotal += $maxVal;
716 }
717 }
718 }
719
720 $form->_priceSet['optionsMaxValueTotal'] = $optionsMaxValueTotal;
721 if ($optionsMaxValueTotal) {
722 $form->_priceSet['optionsMaxValueDetails'] = $optionsMaxValueDetails;
723 }
724 }
725 $form->set('priceSetId', $form->_priceSetId);
726 $form->set('priceSet', $form->_priceSet);
727
728 return $priceSetId;
729 }
730 return FALSE;
731 }
732
ffd93213 733 /**
003ca729
EM
734 * Get line item purchase information.
735 *
736 * This function takes the input parameters and interprets out of it what has been purchased.
737 *
ffd93213 738 * @param $fields
003ca729
EM
739 * This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
740 * And, it would make sense to introduce caching into that function and call it from here rather than
741 * require the $fields array which is passed from pillar to post around the form in order to pass it in here.
c490a46a 742 * @param array $params
003ca729 743 * Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
ffd93213 744 * @param $lineItem
003ca729 745 * Line item array to be altered.
ffd93213 746 * @param string $component
003ca729
EM
747 * This parameter appears to only be relevant to determining whether memberships should be auto-renewed.
748 * (and is effectively a boolean for 'is_membership' which could be calculated from the line items.)
ffd93213 749 */
079dc599 750 public static function processAmount($fields, &$params, &$lineItem, $component = '') {
6a488035 751 // using price set
dc428161 752 $totalPrice = $totalTax = 0;
6a488035
TO
753 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
754 if ($component) {
755 $autoRenew = array();
756 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
757 }
758 foreach ($fields as $id => $field) {
a7488080 759 if (empty($params["price_{$id}"]) ||
6a488035
TO
760 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
761 ) {
762 // skip if nothing was submitted for this field
763 continue;
764 }
765
766 switch ($field['html_type']) {
767 case 'Text':
be45c8b4
EM
768 $firstOption = reset($field['options']);
769 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
6a488035 770 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
dc428161 771 if (CRM_Utils_Array::value('tax_rate', $field['options'][key($field['options'])])) {
772 $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
773 $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
774 }
049db839 775 if (CRM_Utils_Array::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
776 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
777 if (array_key_exists($params['financial_type_id'], $taxRates)) {
778 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
779 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
cce6ec9f 780 $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
049db839 781 $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
782 $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
783 }
784 }
3b5db8ce 785 $totalPrice += $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[key($field['options'])]);
6a488035
TO
786 break;
787
788 case 'Radio':
789 //special case if user select -none-
790 if ($params["price_{$id}"] <= 0) {
791 continue;
792 }
793 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
794 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
795 $optionLabel = CRM_Utils_Array::value('label', $field['options'][$optionValueId]);
796 $params['amount_priceset_level_radio'] = array();
797 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
798 if (isset($radioLevel)) {
799 $radioLevel = array_merge($radioLevel,
800 array_keys($params['amount_priceset_level_radio'])
801 );
802 }
803 else {
804 $radioLevel = array_keys($params['amount_priceset_level_radio']);
805 }
806 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
dc428161 807 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
808 $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
809 $totalTax += $field['options'][$optionValueId]['tax_amount'];
c40e1ff4 810 if (CRM_Utils_Array::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
811 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
812 }
dc428161 813 }
c40e1ff4 814 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
cde484fd
DL
815 if (
816 $component &&
a6c4ca20 817 // auto_renew exists and is empty in some workflows, which php treat as a 0
28156120 818 // and hence we explicitly check to see if auto_renew is numeric
cde484fd
DL
819 isset($lineItem[$optionValueId]['auto_renew']) &&
820 is_numeric($lineItem[$optionValueId]['auto_renew'])
821 ) {
6a488035
TO
822 $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
823 }
824 break;
825
826 case 'Select':
827 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
828 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
829 $optionLabel = $field['options'][$optionValueId]['label'];
830 $params['amount_priceset_level_select'] = array();
831 $params['amount_priceset_level_select'][CRM_Utils_Array::key(1, $params["price_{$id}"])] = $optionLabel;
832 if (isset($selectLevel)) {
833 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
834 }
835 else {
836 $selectLevel = array_keys($params['amount_priceset_level_select']);
837 }
838 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
dc428161 839 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
840 $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
841 $totalTax += $field['options'][$optionValueId]['tax_amount'];
842 }
c40e1ff4 843 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
cde484fd
DL
844 if (
845 $component &&
846 isset($lineItem[$optionValueId]['auto_renew']) &&
847 is_numeric($lineItem[$optionValueId]['auto_renew'])
848 ) {
6a488035
TO
849 $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
850 }
851 break;
852
853 case 'CheckBox':
854 $params['amount_priceset_level_checkbox'] = $optionIds = array();
855 foreach ($params["price_{$id}"] as $optionId => $option) {
856 $optionIds[] = $optionId;
857 $optionLabel = $field['options'][$optionId]['label'];
858 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
859 if (isset($checkboxLevel)) {
860 $checkboxLevel = array_unique(array_merge(
353ffa53
TO
861 $checkboxLevel,
862 array_keys($params['amount_priceset_level_checkbox'])
6a488035
TO
863 )
864 );
865 }
866 else {
867 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
868 }
869 }
870 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
871 foreach ($optionIds as $optionId) {
dc428161 872 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionId])) {
873 $lineItem = self::setLineItem($field, $lineItem, $optionId);
874 $totalTax += $field['options'][$optionId]['tax_amount'];
875 }
c40e1ff4 876 $totalPrice += $lineItem[$optionId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionId]);
cde484fd
DL
877 if (
878 $component &&
879 isset($lineItem[$optionId]['auto_renew']) &&
880 is_numeric($lineItem[$optionId]['auto_renew'])
881 ) {
6a488035
TO
882 $autoRenew[$lineItem[$optionId]['auto_renew']] += $lineItem[$optionId]['line_total'];
883 }
884 }
885 break;
886 }
887 }
888
889 $amount_level = array();
890 $totalParticipant = 0;
891 if (is_array($lineItem)) {
892 foreach ($lineItem as $values) {
893 $totalParticipant += $values['participant_count'];
2b308818
DG
894 // This is a bit nasty. The logic of 'quick config' was because price set configuration was
895 // (and still is) too difficult to replace the 'quick config' price set configuration on the contribution
896 // page.
897 //
898 // However, because the quick config concept existed all sorts of logic was hung off it
899 // and function behaviour sometimes depends on whether 'price set' is set - although actually it
900 // is always set at the functional level. In this case we are dealing with the default 'quick config'
901 // price set having a label of 'Contribution Amount' which could wind up creating a 'funny looking' label.
902 // The correct answer is probably for it to have an empty label in the DB - the label is never shown so it is a
903 // place holder.
904 //
905 // But, in the interests of being careful when capacity is low - avoiding the known default value
906 // will get us by.
907 // Crucially a test has been added so a better solution can be implemented later with some comfort.
c039f658 908 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
2b308818
DG
909 if ($values['label'] != ts('Contribution Amount')) {
910 $amount_level[] = $values['label'] . ' - ' . (float) $values['qty'];
911 }
6a488035
TO
912 }
913 }
914
915 $displayParticipantCount = '';
916 if ($totalParticipant > 0) {
917 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
918 }
c039f658 919 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
c0214b81 920 if (!empty($amount_level)) {
0aa9b939 921 $params['amount_level'] = CRM_Utils_Array::implodePadded($amount_level);
c0214b81 922 if (!empty($displayParticipantCount)) {
d7a867a8 923 $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
c0214b81 924 }
2b308818 925 }
85d3367a 926 $params['amount'] = CRM_Utils_Money::format($totalPrice, NULL, NULL, TRUE);
dc428161 927 $params['tax_amount'] = $totalTax;
6a488035
TO
928 if ($component) {
929 foreach ($autoRenew as $dontCare => $eachAmount) {
930 if (!$eachAmount) {
cde484fd 931 unset($autoRenew[$dontCare]);
6a488035
TO
932 }
933 }
481a74f4 934 if (count($autoRenew) > 1) {
6a488035
TO
935 $params['autoRenew'] = $autoRenew;
936 }
937 }
938 }
939
c039f658 940 /**
941 * Get the text to record for amount level.
942 *
943 * @param array $params
944 * Submitted parameters
945 * - priceSetId is required to be set in the calling function
946 * (we don't e-notice check it to enforce that - all payments DO have a price set - even if it is the
947 * default one & this function asks that be set if it is the case).
948 *
949 * @return string
950 * Text for civicrm_contribution.amount_level field.
951 */
952 public static function getAmountLevelText($params) {
953 $priceSetID = $params['priceSetId'];
954 $priceFieldSelection = self::filterPriceFieldsFromParams($priceSetID, $params);
955 $priceFieldMetadata = self::getCachedPriceSetDetail($priceSetID);
8c632a5d 956 $displayParticipantCount = NULL;
0f8a0349 957
c039f658 958 $amount_level = array();
959 foreach ($priceFieldMetadata['fields'] as $field) {
960 if (!empty($priceFieldSelection[$field['id']])) {
0f8a0349 961 $qtyString = '';
c039f658 962 if ($field['is_enter_qty']) {
963 $qtyString = ' - ' . (float) $params['price_' . $field['id']];
964 }
965 // We deliberately & specifically exclude contribution amount as it has a specific meaning.
966 // ie. it represents the default price field for a contribution. Another approach would be not
967 // to give it a label if we don't want it to show.
968 if ($field['label'] != ts('Contribution Amount')) {
969 $amount_level[] = $field['label'] . $qtyString;
970 }
971 }
972 }
973 return CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
974 }
975
976 /**
977 * Get the fields relevant to the price field from the parameters.
978 *
979 * E.g we are looking for price_5 => 7 out of a big array of input parameters.
980 *
981 * @param int $priceSetID
982 * @param array $params
983 *
984 * @return array
985 * Price fields found in the params array
986 */
987 public static function filterPriceFieldsFromParams($priceSetID, $params) {
988 $priceSet = self::getCachedPriceSetDetail($priceSetID);
989 $return = array();
990 foreach ($priceSet['fields'] as $field) {
991 if (!empty($params['price_' . $field['id']])) {
992 $return[$field['id']] = $params['price_' . $field['id']];
993 }
994 }
995 return $return;
996 }
997
998 /**
999 * Wrapper for getSetDetail with caching.
1000 *
1001 * We seem to be passing this array around in a painful way - presumably to avoid the hit
1002 * of loading it - so lets make it callable with caching.
1003 *
1004 * Why not just add caching to the other function? We could do - it just seemed a bit unclear the best caching pattern
1005 * & the function was already pretty fugly. Also, I feel like we need to migrate the interaction with price-sets into
1006 * a more granular interaction - ie. retrieve specific data using specific functions on this class & have the form
1007 * think less about the price sets.
1008 *
1009 * @param int $priceSetID
1010 *
1011 * @return array
1012 */
1013 public static function getCachedPriceSetDetail($priceSetID) {
1014 $cacheKey = __CLASS__ . __FUNCTION__ . '_' . $priceSetID;
1015 $cache = CRM_Utils_Cache::singleton();
1016 $values = (array) $cache->get($cacheKey);
1017 if (empty($values)) {
1018 $data = self::getSetDetail($priceSetID);
1019 $values = $data[$priceSetID];
1020 $cache->set($cacheKey, $values);
1021 }
1022 return $values;
1023 }
1024
6a488035 1025 /**
100fef9d 1026 * Build the price set form.
6a488035 1027 *
e0c1764e 1028 * @param CRM_Core_Form $form
dd244018 1029 *
355ba699 1030 * @return void
6a488035 1031 */
00be9182 1032 public static function buildPriceSet(&$form) {
6a488035 1033 $priceSetId = $form->get('priceSetId');
6a488035
TO
1034 if (!$priceSetId) {
1035 return;
1036 }
1037
1038 $validFieldsOnly = TRUE;
1039 $className = CRM_Utils_System::getClassName($form);
1040 if (in_array($className, array(
353ffa53 1041 'CRM_Contribute_Form_Contribution',
acb1052e 1042 'CRM_Member_Form_Membership',
353ffa53 1043 ))) {
6a488035
TO
1044 $validFieldsOnly = FALSE;
1045 }
1046
353ffa53
TO
1047 $priceSet = self::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
1048 $form->_priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
883e4763 1049 $validPriceFieldIds = array_keys($form->_priceSet['fields']);
6a488035 1050 $form->_quickConfig = $quickConfig = 0;
9da8dc8c 1051 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
6a488035
TO
1052 $quickConfig = 1;
1053 }
1054
1055 $form->assign('quickConfig', $quickConfig);
1056 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
1057 $form->_quickConfig = $quickConfig;
1058 }
1059 $form->assign('priceSet', $form->_priceSet);
1060
1061 $component = 'contribution';
1062 if ($className == 'CRM_Member_Form_Membership') {
1063 $component = 'membership';
1064 }
1065
1066 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
1067 $feeBlock = &$form->_values['fee'];
1068 if (!empty($form->_useForMember)) {
1069 $component = 'membership';
1070 }
1071 }
1072 else {
1073 $feeBlock = &$form->_priceSet['fields'];
1074 }
66af7c48
PN
1075 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
1076 foreach ($feeBlock as $key => $value) {
1077 foreach ($value['options'] as $k => $options) {
1078 if (!CRM_Core_Permission::check('add contributions of type ' . CRM_Contribute_PseudoConstant::financialType($options['financial_type_id']))) {
1079 unset($feeBlock[$key]['options'][$k]);
1080 }
1081 }
1082 if (empty($feeBlock[$key]['options'])) {
1083 unset($feeBlock[$key]);
e1a89dfd 1084 }
4a695b27 1085 }
e1a89dfd 1086 }
6a488035
TO
1087 // call the hook.
1088 CRM_Utils_Hook::buildAmount($component, $form, $feeBlock);
1089
c7b3d063 1090 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
ba1dcfda 1091 $adminFieldVisible = FALSE;
c7b3d063 1092 if (CRM_Core_Permission::check('administer CiviCRM')) {
ba1dcfda 1093 $adminFieldVisible = TRUE;
c7b3d063 1094 }
77b97be7 1095
883e4763 1096 foreach ($feeBlock as $id => $field) {
6a488035 1097 if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
ba1dcfda 1098 (CRM_Utils_Array::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
6a488035
TO
1099 !$validFieldsOnly
1100 ) {
1101 $options = CRM_Utils_Array::value('options', $field);
1102 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
cc509891 1103 $userid = $form->getVar('_membershipContactID');
6a488035
TO
1104 $checklifetime = self::checkCurrentMembership($options, $userid);
1105 if ($checklifetime) {
1106 $form->assign('ispricelifetime', TRUE);
1107 }
1108 }
883e4763 1109 if (!is_array($options) || !in_array($id, $validPriceFieldIds)) {
6a488035
TO
1110 continue;
1111 }
9da8dc8c 1112 CRM_Price_BAO_PriceField::addQuickFormElement($form,
6a488035
TO
1113 'price_' . $field['id'],
1114 $field['id'],
1115 FALSE,
1116 CRM_Utils_Array::value('is_required', $field, FALSE),
1117 NULL,
1118 $options
1119 );
1120 }
1121 }
1122 }
1123
1124 /**
003ca729
EM
1125 * Check the current Membership having end date null.
1126 *
1127 * @param array $options
1128 * @param int $userid
1129 * Probably actually contact ID.
1130 *
1131 * @return bool
6a488035 1132 */
00be9182 1133 public static function checkCurrentMembership(&$options, $userid) {
6a488035 1134 if (!$userid || empty($options)) {
925157c5 1135 return FALSE;
6a488035
TO
1136 }
1137 static $_contact_memberships = array();
003ca729 1138 $checkLifetime = FALSE;
6a488035 1139 foreach ($options as $key => $value) {
a7488080 1140 if (!empty($value['membership_type_id'])) {
6a488035
TO
1141 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
1142 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership::getContactMembership($userid, $value['membership_type_id'], FALSE);
1143 }
1144 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
8cc574cf 1145 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
6a488035 1146 unset($options[$key]);
003ca729 1147 $checkLifetime = TRUE;
6a488035
TO
1148 }
1149 }
1150 }
003ca729 1151 if ($checkLifetime) {
6a488035
TO
1152 return TRUE;
1153 }
1154 else {
1155 return FALSE;
1156 }
1157 }
1158
1159 /**
100fef9d 1160 * Set daefult the price set fields.
6a488035 1161 *
c490a46a 1162 * @param CRM_Core_Form $form
fd31fa4c
EM
1163 * @param $defaults
1164 *
a6c01b45 1165 * @return array
6a488035 1166 */
00be9182 1167 public static function setDefaultPriceSet(&$form, &$defaults) {
6a488035
TO
1168 if (!isset($form->_priceSet) || empty($form->_priceSet['fields'])) {
1169 return $defaults;
1170 }
1171
1172 foreach ($form->_priceSet['fields'] as $key => $val) {
1173 foreach ($val['options'] as $keys => $values) {
cb063506
KJ
1174 // build price field index which is passed via URL
1175 // url format will be appended by "&price_5=11"
1176 $priceFieldName = 'price_' . $values['price_field_id'];
1177 $priceFieldValue = self::getPriceFieldValueFromURL($form, $priceFieldName);
1178 if (!empty($priceFieldValue)) {
034b5cb6 1179 self::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $defaults);
cb063506
KJ
1180 // break here to prevent overwriting of default due to 'is_default'
1181 // option configuration. The value sent via URL get's higher priority.
1182 break;
1183 }
1184 elseif ($values['is_default']) {
034b5cb6 1185 self::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $defaults);
6a488035
TO
1186 }
1187 }
1188 }
1189 return $defaults;
1190 }
1191
034b5cb6
KJ
1192 /**
1193 * Get the value of price field if passed via url
1194 *
1195 * @param string $priceFieldName
1196 * @param string $priceFieldValue
1197 * @param string $priceFieldType
1198 * @param array $defaults
1199 *
1200 * @return void
1201 */
1202 public static function setDefaultPriceSetField($priceFieldName, $priceFieldValue, $priceFieldType, &$defaults) {
1203 if ($priceFieldType == 'CheckBox') {
1204 $defaults[$priceFieldName][$priceFieldValue] = 1;
1205 }
1206 else {
1207 $defaults[$priceFieldName] = $priceFieldValue;
1208 }
1209 }
1210
cb063506
KJ
1211 /**
1212 * Get the value of price field if passed via url
1213 *
1214 * @param CRM_Core_Form $form
1215 * @param string $priceFieldName
1216 *
1217 * @return mixed $priceFieldValue
1218 */
1219 public static function getPriceFieldValueFromURL(&$form, $priceFieldName) {
1220 $priceFieldValue = CRM_Utils_Request::retrieve($priceFieldName, 'String', $form, FALSE, NULL, 'GET');
1221 if (!empty($priceFieldValue)) {
1222 return $priceFieldValue;
1223 }
1224 }
1225
b2cdd843
EM
1226 /**
1227 * Supports event create function by setting up required price sets, not tested but expect
1228 * it will work for contribution page
414c1420
TO
1229 * @param array $params
1230 * As passed to api/bao create fn.
1231 * @param CRM_Core_DAO $entity
1232 * Object for given entity.
1233 * @param string $entityName
1234 * Name of entity - e.g event.
b2cdd843 1235 */
00be9182 1236 public static function setPriceSets(&$params, $entity, $entityName) {
22e263ad 1237 if (empty($params['price_set_id']) || !is_array($params['price_set_id'])) {
b2cdd843
EM
1238 return;
1239 }
1240 // CRM-14069 note that we may as well start by assuming more than one.
1241 // currently the form does not pass in as an array & will be skipped
1242 // test is passing in as an array but I feel the api should have a metadata that allows
1243 // transform of single to array - seems good for managing transitions - in which case all api
1244 // calls that set price_set_id will hit this
1245 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1246 // all separated values, strings, json half-separated values (in participant we hit this)
1247 // to be converted to json @ api layer
1248 $pse = new CRM_Price_DAO_PriceSetEntity();
1249 $pse->entity_table = 'civicrm_' . $entityName;
1250 $pse->entity_id = $entity->id;
1251 while ($pse->fetch()) {
22e263ad 1252 if (!in_array($pse->price_set_id, $params['price_set_id'])) {
b2cdd843
EM
1253 // note an even more aggressive form of this deletion currently happens in event form
1254 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1255 // on the participant record
1256 if (CRM_Price_BAO_PriceSet::removeFrom('civicrm_' . $entityName, $entity->id)) {
ba1dcfda 1257 CRM_Core_BAO_Discount::del($entity->id, 'civicrm_' . $entityName);
b2cdd843
EM
1258 }
1259 }
1260 }
1261 foreach ($params['price_set_id'] as $priceSetID) {
1262 CRM_Price_BAO_PriceSet::addTo('civicrm_' . $entityName, $entity->id, $priceSetID);
1263 //@todo - how should we do this - copied from form
b53cbfbc 1264 //if (!empty($params['price_field_id'])) {
b2cdd843
EM
1265 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1266 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1267 //}
1268 }
1269 }
353ffa53 1270
6a488035 1271 /**
fe482240 1272 * Get field ids of a price set.
6a488035 1273 *
414c1420
TO
1274 * @param int $id
1275 * Price Set id.
6a488035 1276 *
a6c01b45 1277 * @return array
16b10e64 1278 * Array of the field ids
6a488035 1279 *
6a488035
TO
1280 */
1281 public static function getFieldIds($id) {
9da8dc8c 1282 $priceField = new CRM_Price_DAO_PriceField();
6a488035
TO
1283 $priceField->price_set_id = $id;
1284 $priceField->find();
1285 while ($priceField->fetch()) {
1286 $var[] = $priceField->id;
1287 }
1288 return $var;
1289 }
1290
1291 /**
72b3a70c 1292 * Copy a price set, including all the fields
6a488035 1293 *
414c1420
TO
1294 * @param int $id
1295 * The price set id to copy.
6a488035 1296 *
72b3a70c 1297 * @return CRM_Price_DAO_PriceSet
6a488035 1298 */
00be9182 1299 public static function copy($id) {
6a488035
TO
1300 $maxId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1301
1302 $title = ts('[Copy id %1]', array(1 => $maxId + 1));
1303 $fieldsFix = array(
ba1dcfda 1304 'suffix' => array(
353ffa53
TO
1305 'title' => ' ' . $title,
1306 'name' => '__Copy_id_' . ($maxId + 1) . '_',
6a488035
TO
1307 ),
1308 );
1309
9da8dc8c 1310 $copy = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSet',
353ffa53
TO
1311 array('id' => $id),
1312 NULL,
1313 $fieldsFix
6a488035
TO
1314 );
1315
1316 //copying all the blocks pertaining to the price set
9da8dc8c 1317 $copyPriceField = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceField',
353ffa53
TO
1318 array('price_set_id' => $id),
1319 array('price_set_id' => $copy->id)
6a488035
TO
1320 );
1321 if (!empty($copyPriceField)) {
1322 $price = array_combine(self::getFieldIds($id), self::getFieldIds($copy->id));
1323
1324 //copy option group and values
1325 foreach ($price as $originalId => $copyId) {
9da8dc8c 1326 CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceFieldValue',
6a488035
TO
1327 array('price_field_id' => $originalId),
1328 array('price_field_id' => $copyId)
1329 );
1330 }
1331 }
1332 $copy->save();
1333
1334 CRM_Utils_Hook::copy('Set', $copy);
1335 return $copy;
1336 }
1337
1338 /**
fe482240 1339 * check price set permission.
6a488035 1340 *
414c1420
TO
1341 * @param int $sid
1342 * The price set id.
77b97be7
EM
1343 *
1344 * @return bool
6a488035 1345 */
00be9182 1346 public static function checkPermission($sid) {
44c8822b 1347 if ($sid && self::eventPriceSetDomainID()) {
9da8dc8c 1348 $domain_id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
6a488035 1349 if (CRM_Core_Config::domainID() != $domain_id) {
0499b0ad 1350 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
6a488035
TO
1351 }
1352 }
1353 return TRUE;
1354 }
1355
1356 /**
1357 * Get the sum of participant count
1358 * for all fields of given price set.
1359 *
414c1420
TO
1360 * @param int $sid
1361 * The price set id.
6a488035 1362 *
77b97be7
EM
1363 * @param bool $onlyActive
1364 *
1365 * @return int|null|string
6a488035
TO
1366 */
1367 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1368 $count = 0;
1369 if (!$sid) {
1370 return $count;
1371 }
1372
1373 $where = NULL;
1374 if ($onlyActive) {
1375 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1376 }
1377
1378 static $pricesetFieldCount = array();
1379 if (!isset($pricesetFieldCount[$sid])) {
1380 $sql = "
1381 SELECT sum(value.count) as totalCount
1382 FROM civicrm_price_field_value value
1383INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1384INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1385 WHERE pset.id = %1
1386 $where";
1387
1388 $count = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1389 $pricesetFieldCount[$sid] = ($count) ? $count : 0;
1390 }
1391
1392 return $pricesetFieldCount[$sid];
1393 }
1394
ffd93213
EM
1395 /**
1396 * @param $ids
1397 *
1398 * @return array
1399 */
6a488035
TO
1400 public static function getMembershipCount($ids) {
1401 $queryString = "
1402SELECT count( pfv.id ) AS count, pfv.id AS id
1403FROM civicrm_price_field_value pfv
1404INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1405WHERE pfv.id IN ( $ids )
1406GROUP BY mt.member_of_contact_id";
1407
1408 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
1409 $count = array();
1410
1411 while ($crmDAO->fetch()) {
1412 $count[$crmDAO->id] = $crmDAO->count;
1413 }
1414
1415 return $count;
1416 }
1417
1418 /**
fe482240 1419 * Check if auto renew option should be shown.
6a488035 1420 *
8eb1503b 1421 * The auto-renew option should be visible if membership types associated with all the fields has
1422 * been set for auto-renew option.
1423 *
1424 * Auto renew checkbox should be frozen if for all the membership type auto renew is required
1425 *
414c1420
TO
1426 * @param int $priceSetId
1427 * Price set id.
6a488035 1428 *
a6c01b45
CW
1429 * @return int
1430 * $autoRenewOption ( 0:hide, 1:optional 2:required )
6a488035
TO
1431 */
1432 public static function checkAutoRenewForPriceSet($priceSetId) {
8eb1503b 1433 $query = 'SELECT DISTINCT mt.auto_renew, mt.duration_interval, mt.duration_unit,
1434 pf.html_type, pf.id as price_field_id
6a488035
TO
1435 FROM civicrm_price_field_value pfv
1436 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1437 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1438 WHERE pf.price_set_id = %1
1439 AND pf.is_active = 1
8eb1503b 1440 AND pfv.is_active = 1
1441 ORDER BY price_field_id';
6a488035
TO
1442
1443 $params = array(1 => array($priceSetId, 'Integer'));
1444
353ffa53 1445 $dao = CRM_Core_DAO::executeQuery($query, $params);
8eb1503b 1446
6a488035 1447 $autoRenewOption = 2;
8eb1503b 1448 $priceFields = array();
6a488035
TO
1449 while ($dao->fetch()) {
1450 if (!$dao->auto_renew) {
8eb1503b 1451 // If any one can't be renewed none can.
1452 return 0;
6a488035
TO
1453 }
1454 if ($dao->auto_renew == 1) {
1455 $autoRenewOption = 1;
1456 }
1457
8eb1503b 1458 if ($dao->html_type == 'Checkbox' && !in_array($dao->duration_interval . $dao->duration_unit, $priceFields[$dao->price_field_id])) {
1459 // Checkbox fields cannot support auto-renew if they have more than one duration configuration
1460 // as more than one can be selected. Radio and select are either-or so they can have more than one duration.
1461 return 0;
1462 }
1463 $priceFields[$dao->price_field_id][] = $dao->duration_interval . $dao->duration_unit;
1464 foreach ($priceFields as $priceFieldID => $durations) {
1465 if ($priceFieldID != $dao->price_field_id && !in_array($dao->duration_interval . $dao->duration_unit, $durations)) {
1466 // Another price field has a duration configuration that differs so we can't offer auto-renew.
1467 return 0;
1468 }
1469 }
6a488035
TO
1470 }
1471
8eb1503b 1472 return $autoRenewOption;
6a488035
TO
1473 }
1474
1475 /**
fe482240 1476 * Retrieve auto renew frequency and interval.
6a488035 1477 *
414c1420
TO
1478 * @param int $priceSetId
1479 * Price set id.
6a488035 1480 *
a6c01b45
CW
1481 * @return array
1482 * associate array of frequency interval and unit
6a488035
TO
1483 */
1484 public static function getRecurDetails($priceSetId) {
1485 $query = 'SELECT mt.duration_interval, mt.duration_unit
1486 FROM civicrm_price_field_value pfv
1487 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1488 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1489 WHERE pf.price_set_id = %1 LIMIT 1';
1490
1491 $params = array(1 => array($priceSetId, 'Integer'));
1492 $dao = CRM_Core_DAO::executeQuery($query, $params);
1493 $dao->fetch();
1494 return array($dao->duration_interval, $dao->duration_unit);
1495 }
1496
ffd93213
EM
1497 /**
1498 * @return object
1499 */
00be9182 1500 public static function eventPriceSetDomainID() {
d356cdeb 1501 return Civi::settings()->get('event_price_set_domain_id');
6a488035
TO
1502 }
1503
1504 /**
fe482240 1505 * Update the is_quick_config flag in the db.
6a488035 1506 *
414c1420
TO
1507 * @param int $id
1508 * Id of the database record.
acb1052e 1509 * @param bool $isQuickConfig we want to set the is_quick_config field.
414c1420 1510 * Value we want to set the is_quick_config field.
6a488035 1511 *
a6c01b45 1512 * @return Object
b44e3f84 1513 * DAO object on success, null otherwise
6a488035 1514 */
00be9182 1515 public static function setIsQuickConfig($id, $isQuickConfig) {
9da8dc8c 1516 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
6a488035
TO
1517 }
1518
1519 /**
f72e6e2c 1520 * Check if price set id provides option for user to select both auto-renew and non-auto-renew memberships
6a488035 1521 *
003ca729
EM
1522 * @param int $id
1523 *
1524 * @return bool
6a488035 1525 */
f72e6e2c
EM
1526 public static function isMembershipPriceSetContainsMixOfRenewNonRenew($id) {
1527 $membershipTypes = self::getMembershipTypesFromPriceSet($id);
1528 if (!empty($membershipTypes['autorenew']) && !empty($membershipTypes['non_renew'])) {
1529 return TRUE;
6a488035 1530 }
ba1dcfda 1531 return FALSE;
6a488035
TO
1532 }
1533
37b11065
EM
1534 /**
1535 * Get an array of the membership types in a price set.
1536 *
1537 * @param int $id
1538 *
1539 * @return array(
1540 * Membership types in the price set
1541 */
1542 public static function getMembershipTypesFromPriceSet($id) {
1543 $query
1544 = "SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1545FROM civicrm_price_field_value pfv
1546LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1547LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1548LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1549WHERE ps.id = %1
1550";
1551
1552 $params = array(1 => array($id, 'Integer'));
1553 $dao = CRM_Core_DAO::executeQuery($query, $params);
1554
1555 $membershipTypes = array(
1556 'all' => array(),
1557 'autorenew' => array(),
1558 'autorenew_required' => array(),
1559 'autorenew_optional' => array(),
1560 );
1561 while ($dao->fetch()) {
1562 if (empty($dao->membership_type_id)) {
1563 continue;
1564 }
1565 $membershipTypes['all'][] = $dao->membership_type_id;
1566 if (!empty($dao->auto_renew)) {
1567 $membershipTypes['autorenew'][] = $dao->membership_type_id;
1568 if ($dao->auto_renew == 2) {
1569 $membershipTypes['autorenew_required'][] = $dao->membership_type_id;
1570 }
1571 else {
1572 $membershipTypes['autorenew_optional'][] = $dao->membership_type_id;
1573 }
1574 }
1575 else {
1576 $membershipTypes['non_renew'][] = $dao->membership_type_id;
1577 }
1578 }
1579 return $membershipTypes;
1580 }
1581
e0c1764e 1582 /**
c6914066
PN
1583 * Copy priceSet when event/contibution page is copied
1584 *
414c1420
TO
1585 * @param string $baoName
1586 * BAO name.
1587 * @param int $id
1588 * Old event/contribution page id.
1589 * @param int $newId
1590 * Newly created event/contribution page id.
c6914066 1591 */
00be9182 1592 public static function copyPriceSet($baoName, $id, $newId) {
9da8dc8c 1593 $priceSetId = CRM_Price_BAO_PriceSet::getFor($baoName, $id);
c6914066 1594 if ($priceSetId) {
9da8dc8c 1595 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
22e263ad 1596 if ($isQuickConfig) {
37326fa1 1597 $copyPriceSet = CRM_Price_BAO_PriceSet::copy($priceSetId);
9da8dc8c 1598 CRM_Price_BAO_PriceSet::addTo($baoName, $newId, $copyPriceSet->id);
44c8822b 1599 }
c6914066 1600 else {
9da8dc8c 1601 $copyPriceSet = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSetEntity',
c6914066
PN
1602 array(
1603 'entity_id' => $id,
1604 'entity_table' => $baoName,
1605 ),
1606 array('entity_id' => $newId)
1607 );
1608 }
1609 // copy event discount
1610 if ($baoName == 'civicrm_event') {
1611 $discount = CRM_Core_BAO_Discount::getOptionGroup($id, 'civicrm_event');
1612 foreach ($discount as $discountId => $setId) {
1613
9da8dc8c 1614 $copyPriceSet = &CRM_Price_BAO_PriceSet::copy($setId);
44c8822b 1615
28156120 1616 CRM_Core_DAO::copyGeneric(
c6914066
PN
1617 'CRM_Core_DAO_Discount',
1618 array(
1619 'id' => $discountId,
1620 ),
1621 array(
1622 'entity_id' => $newId,
1623 'price_set_id' => $copyPriceSet->id,
1624 )
1625 );
1626 }
1627 }
1628 }
1629 }
dc428161 1630
d424ffde 1631 /**
fe482240 1632 * Function to set tax_amount and tax_rate in LineItem.
d424ffde
CW
1633 *
1634 * @param array $field
1635 * @param array $lineItem
1636 * @param int $optionValueId
1637 *
1638 * @return array
dc428161 1639 */
00be9182 1640 public static function setLineItem($field, $lineItem, $optionValueId) {
dc428161 1641 if ($field['html_type'] == 'Text') {
1642 $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
1643 }
1644 else {
1645 $taxAmount = $field['options'][$optionValueId]['tax_amount'];
1646 }
1647 $taxRate = $field['options'][$optionValueId]['tax_rate'];
dc428161 1648 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1649 $lineItem[$optionValueId]['tax_rate'] = $taxRate;
1650
1651 return $lineItem;
1652 }
96025800 1653
6a488035 1654}