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