INFRA-132 - CRM/Pledge - Convert single-line @param to multi-line
[civicrm-core.git] / CRM / Price / BAO / PriceSet.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 * Business object for managing price sets
38 *
39 */
9da8dc8c 40class CRM_Price_BAO_PriceSet extends CRM_Price_DAO_PriceSet {
6a488035 41
71ba92c4 42 /**
100fef9d 43 * Static field for default price set details
71ba92c4
PN
44 *
45 * @var array
46 * @static
47 */
48 static $_defaultPriceSet = NULL;
49
6a488035 50 /**
100fef9d 51 * Class constructor
6a488035 52 */
00be9182 53 public function __construct() {
6a488035
TO
54 parent::__construct();
55 }
56
57 /**
100fef9d 58 * Takes an associative array and creates a price set object
6a488035
TO
59 *
60 * @param array $params (reference) an assoc array of name/value pairs
61 *
c490a46a 62 * @return CRM_Price_DAO_PriceSet object
6a488035
TO
63 * @static
64 */
00be9182 65 public static function create(&$params) {
e0c1764e
EM
66 if(empty($params['id']) && empty($params['name'])) {
67 $params['name'] = CRM_Utils_String::munge($params['title'], '_', 242);
68 }
e10ac060 69 if (!empty($params['extends']) && is_array($params['extends'])) {
076809e3
JV
70 $params['extends'] = CRM_Utils_Array::implodePadded($params['extends']);
71 }
9da8dc8c 72 $priceSetBAO = new CRM_Price_BAO_PriceSet();
6a488035
TO
73 $priceSetBAO->copyValues($params);
74 if (self::eventPriceSetDomainID()) {
75 $priceSetBAO->domain_id = CRM_Core_Config::domainID();
76 }
77 return $priceSetBAO->save();
78 }
79
80 /**
c490a46a 81 * Fetch object based on array of properties
6a488035
TO
82 *
83 * @param array $params (reference ) an assoc array of name/value pairs
84 * @param array $defaults (reference ) an assoc array to hold the flattened values
85 *
c490a46a 86 * @return CRM_Price_DAO_PriceSet object
6a488035
TO
87 * @static
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 /**
100fef9d 94 * Update the is_active flag in the db
6a488035 95 *
6c8f6e67
EM
96 * @param int $id id of the database record
97 * @param $isActive
98 *
99 * @internal param bool $is_active value we want to set the is_active field
6a488035
TO
100 *
101 * @return Object DAO object on sucess, null otherwise
102 * @static
6a488035 103 */
00be9182 104 public static function setIsActive($id, $isActive) {
9da8dc8c 105 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
6a488035
TO
106 }
107
108 /**
109 * Calculate the default price set id
110 * assigned to the contribution/membership etc
111 *
112 * @param string $entity
113 *
e0c1764e 114 * @return array $defaultPriceSet default price set
6a488035 115 *
6a488035
TO
116 * @static
117 *
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
PN
139 self::$_defaultPriceSet[$entity][$dao->priceFieldValueID] = array(
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,
148 );
6a488035
TO
149 }
150
71ba92c4 151 return self::$_defaultPriceSet[$entity];
6a488035
TO
152 }
153
154 /**
155 * Get the price set title.
156 *
157 * @param int $id id of price set
158 *
159 * @return string title
160 *
6a488035
TO
161 * @static
162 *
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 *
da6b46f4 171 * @param int $id id of price set
e0c1764e 172 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
6a488035
TO
173 *
174 * @return array
175 */
176 public static function &getUsedBy($id, $simpleReturn = FALSE) {
177 $usedBy = $forms = $tables = array();
178 $queryString = "
179SELECT entity_table, entity_id
180FROM civicrm_price_set_entity
181WHERE price_set_id = %1";
182 $params = array(1 => array($id, 'Integer'));
183 $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
184
185 while ($crmFormDAO->fetch()) {
186 $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
187 $tables[] = $crmFormDAO->entity_table;
188 }
189 // Return only tables
190 if ($simpleReturn == 'table') {
191 return $tables;
192 }
193 if (empty($forms)) {
194 $queryString = "
195SELECT cli.entity_table, cli.entity_id
196FROM civicrm_line_item cli
197LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
198WHERE cpf.price_set_id = %1";
199 $params = array(1 => array($id, 'Integer'));
200 $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
201 while ($crmFormDAO->fetch()) {
202 $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
203 $tables[] = $crmFormDAO->entity_table;
204 }
205 if (empty($forms)) {
206 return $usedBy;
207 }
208 }
209 // Return only entity data
210 if ($simpleReturn == 'entity') {
211 return $forms;
212 }
213 foreach ($forms as $table => $entities) {
214 switch ($table) {
215 case 'civicrm_event':
216 $ids = implode(',', $entities);
c34e4bb4 217 $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
218FROM civicrm_event ce
219LEFT JOIN civicrm_option_value ON
220 ( ce.event_type_id = civicrm_option_value.value )
221LEFT JOIN civicrm_option_group ON
222 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
223WHERE
224 civicrm_option_group.name = 'event_type' AND
6a488035
TO
225 ce.id IN ($ids) AND
226 ce.is_active = 1;";
227 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
228 while ($crmDAO->fetch()) {
c34e4bb4
PJ
229 if ($crmDAO->isTemplate) {
230 $usedBy['civicrm_event_template'][$crmDAO->id]['title'] = $crmDAO->templateTitle;
231 $usedBy['civicrm_event_template'][$crmDAO->id]['eventType'] = $crmDAO->eventType;
232 $usedBy['civicrm_event_template'][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
233 }
234 else {
235 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
236 $usedBy[$table][$crmDAO->id]['eventType'] = $crmDAO->eventType;
237 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
238 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
239 $usedBy[$table][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
240 }
6a488035
TO
241 }
242 break;
243
244 case 'civicrm_contribution_page':
245 $ids = implode(',', $entities);
246 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
247FROM civicrm_contribution_page cp, civicrm_financial_type ct
cde484fd 248WHERE ct.id = cp.financial_type_id AND
6a488035
TO
249 cp.id IN ($ids) AND
250 cp.is_active = 1;";
251 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
252 while ($crmDAO->fetch()) {
253 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
254 $usedBy[$table][$crmDAO->id]['type'] = $crmDAO->type;
255 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
256 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
257 }
258 break;
259
260 case 'civicrm_contribution':
261 case 'civicrm_membership':
262 case 'civicrm_participant':
263 $usedBy[$table] = 1;
264 break;
265
266 default:
267 CRM_Core_Error::fatal("$table is not supported in PriceSet::usedBy()");
268 break;
269 }
270 }
271
272 return $usedBy;
273 }
274
275 /**
276 * Delete the price set
277 *
278 * @param int $id Price Set id
279 *
280 * @return boolean false if fields exist for this set, true if the
281 * set could be deleted
282 *
6a488035
TO
283 * @static
284 */
285 public static function deleteSet($id) {
286 // remove from all inactive forms
287 $usedBy = self::getUsedBy($id);
288 if (isset($usedBy['civicrm_event'])) {
289 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
290 $eventDAO = new CRM_Event_DAO_Event();
291 $eventDAO->id = $eventId;
292 $eventDAO->find();
293 while ($eventDAO->fetch()) {
294 self::removeFrom('civicrm_event', $eventDAO->id);
295 }
296 }
297 }
298
299 // delete price fields
9da8dc8c 300 $priceField = new CRM_Price_DAO_PriceField();
6a488035
TO
301 $priceField->price_set_id = $id;
302 $priceField->find();
303 while ($priceField->fetch()) {
304 // delete options first
9da8dc8c 305 CRM_Price_BAO_PriceField::deleteField($priceField->id);
6a488035
TO
306 }
307
9da8dc8c 308 $set = new CRM_Price_DAO_PriceSet();
6a488035
TO
309 $set->id = $id;
310 return $set->delete();
311 }
312
313 /**
314 * Link the price set with the specified table and id
315 *
316 * @param string $entityTable
317 * @param integer $entityId
318 * @param integer $priceSetId
319 *
320 * @return bool
321 */
322 public static function addTo($entityTable, $entityId, $priceSetId) {
323 // verify that the price set exists
9da8dc8c 324 $dao = new CRM_Price_DAO_PriceSet();
6a488035
TO
325 $dao->id = $priceSetId;
326 if (!$dao->find()) {
327 return FALSE;
328 }
329 unset($dao);
330
9da8dc8c 331 $dao = new CRM_Price_DAO_PriceSetEntity();
6a488035
TO
332 // find if this already exists
333 $dao->entity_id = $entityId;
334 $dao->entity_table = $entityTable;
335 $dao->find(TRUE);
336
337 // add or update price_set_id
338 $dao->price_set_id = $priceSetId;
339 return $dao->save();
340 }
341
342 /**
343 * Delete price set for the given entity and id
344 *
345 * @param string $entityTable
346 * @param integer $entityId
77b97be7
EM
347 *
348 * @return mixed
6a488035
TO
349 */
350 public static function removeFrom($entityTable, $entityId) {
9da8dc8c 351 $dao = new CRM_Price_DAO_PriceSetEntity();
6a488035
TO
352 $dao->entity_table = $entityTable;
353 $dao->entity_id = $entityId;
354 return $dao->delete();
355 }
356
357 /**
358 * Find a price_set_id associatied with the given table, id and usedFor
359 * Used For value for events:1, contribution:2, membership:3
360 *
361 * @param string $entityTable
77b97be7
EM
362 * @param int $entityId
363 * @param int $usedFor ( price set that extends/used for particular component )
364 *
365 * @param null $isQuickConfig
366 * @param null $setName
6a488035
TO
367 *
368 * @return integer|false price_set_id, or false if none found
369 */
370 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
371 if (!$entityTable || !$entityId) {
372 return FALSE;
373 }
374
375 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
376 FROM civicrm_price_set ps
377 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
378 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
379 if ($isQuickConfig) {
380 $sql .= ' AND ps.is_quick_config = 0 ';
381 }
382 $params = array(1 => array($entityTable, 'String'),
383 2 => array($entityId, 'Integer'),
384 );
385 if ($usedFor) {
386 $sql .= " AND ps.extends LIKE '%%3%' ";
387 $params[3] = array($usedFor, 'Integer');
388 }
389
390 $dao = CRM_Core_DAO::executeQuery($sql, $params);
391 $dao->fetch();
392 $setName = (isset($dao->price_set_name)) ? $dao->price_set_name : FALSE;
393 return (isset($dao->price_set_id)) ? $dao->price_set_id : FALSE;
394 }
395
396 /**
e0c1764e 397 * Find a price_set_id associated with the given option value or field ID
6a488035
TO
398 *
399 * @param array $params (reference) an assoc array of name/value pairs
400 * array may contain either option id or
401 * price field id
402 *
e0c1764e 403 * @return integer|NULL price set id on success, null otherwise
6a488035 404 * @static
6a488035
TO
405 */
406 public static function getSetId(&$params) {
407 $fid = NULL;
408
409 if ($oid = CRM_Utils_Array::value('oid', $params)) {
9da8dc8c 410 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
6a488035
TO
411 $fieldValue->id = $oid;
412 if ($fieldValue->find(TRUE)) {
413 $fid = $fieldValue->price_field_id;
414 }
415 }
416 else {
417 $fid = CRM_Utils_Array::value('fid', $params);
418 }
419
420 if (isset($fid)) {
9da8dc8c 421 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
6a488035
TO
422 }
423
424 return NULL;
425 }
426
427 /**
428 * Return an associative array of all price sets
429 *
77b97be7
EM
430 * @param bool $withInactive whether or not to include inactive entries
431 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
6a488035
TO
432 *
433 * @return array associative array of id => name
434 */
435 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE) {
436 $query = '
437 SELECT
438 DISTINCT ( price_set_id ) as id, title
439 FROM
440 civicrm_price_field,
441 civicrm_price_set
442 WHERE
443 civicrm_price_set.id = civicrm_price_field.price_set_id AND is_quick_config = 0 ';
444
445 if (!$withInactive) {
446 $query .= ' AND civicrm_price_set.is_active = 1 ';
447 }
448
449 if (self::eventPriceSetDomainID()) {
450 $query .= ' AND civicrm_price_set.domain_id = ' . CRM_Core_Config::domainID();
451 }
452
453 $priceSets = array();
454
455 if ($extendComponentName) {
456 $componentId = CRM_Core_Component::getComponentID($extendComponentName);
457 if (!$componentId) {
458 return $priceSets;
459 }
460 $query .= " AND civicrm_price_set.extends LIKE '%$componentId%' ";
461 }
462
463 $dao = CRM_Core_DAO::executeQuery($query);
464 while ($dao->fetch()) {
465 $priceSets[$dao->id] = $dao->title;
466 }
467 return $priceSets;
468 }
469
470 /**
471 * Get price set details
472 *
473 * An array containing price set details (including price fields) is returned
474 *
100fef9d 475 * @param int $setID
2a6da8d7
EM
476 * @param bool $required
477 * @param bool $validOnly
478 *
479 * @internal param int $setId - price set id whose details are needed
6a488035
TO
480 *
481 * @return array $setTree - array consisting of field details
482 */
483 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
484 // create a new tree
485 $setTree = array();
6a488035
TO
486
487 $priceFields = array(
488 'id',
489 'name',
490 'label',
491 'html_type',
492 'is_enter_qty',
493 'help_pre',
494 'help_post',
495 'weight',
496 'is_display_amounts',
497 'options_per_line',
498 'is_active',
499 'active_on',
500 'expire_on',
501 'javascript',
502 'visibility_id',
503 'is_required',
504 );
505 if ($required == TRUE) {
506 $priceFields[] = 'is_required';
507 }
508
509 // create select
510 $select = 'SELECT ' . implode(',', $priceFields);
511 $from = ' FROM civicrm_price_field';
512
513 $params = array();
514 $params[1] = array($setID, 'Integer');
515 $where = '
516WHERE price_set_id = %1
517AND is_active = 1
518';
519 $dateSelect = '';
520 if ($validOnly) {
521 $currentTime = date('YmdHis');
522 $dateSelect = "
523AND ( active_on IS NULL OR active_on <= {$currentTime} )
524AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
525";
526 }
527
528 $orderBy = ' ORDER BY weight';
529
530 $sql = $select . $from . $where . $dateSelect . $orderBy;
531
532 $dao = CRM_Core_DAO::executeQuery($sql, $params);
533
534 $visibility = CRM_Core_PseudoConstant::visibility('name');
535 while ($dao->fetch()) {
536 $fieldID = $dao->id;
537
538 $setTree[$setID]['fields'][$fieldID] = array();
539 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
540
541 foreach ($priceFields as $field) {
542 if ($field == 'id' || is_null($dao->$field)) {
543 continue;
544 }
545
546 if ($field == 'visibility_id') {
547 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
548 }
549 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
550 }
9da8dc8c 551 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField::getOptions($fieldID, FALSE);
6a488035
TO
552 }
553
554 // also get the pre and post help from this price set
555 $sql = "
556SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
557FROM civicrm_price_set
558WHERE id = %1";
559 $dao = CRM_Core_DAO::executeQuery($sql, $params);
560 if ($dao->fetch()) {
561 $setTree[$setID]['extends'] = $dao->extends;
157b21d8 562 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id;
6a488035
TO
563 $setTree[$setID]['help_pre'] = $dao->help_pre;
564 $setTree[$setID]['help_post'] = $dao->help_post;
565 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config;
566 }
567 return $setTree;
568 }
569
85020e43
EM
570 /**
571 * Get the Price Field ID. We call this function when more than one being present would represent an error
572 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
573 * @param array $priceSet
574 *
575 * @throws CRM_Core_Exception
576 * @return int
577 */
00be9182 578 public static function getOnlyPriceFieldID(array $priceSet) {
85020e43
EM
579 if(count($priceSet['fields']) > 1) {
580 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
581 }
582 return (int) implode('_', array_keys($priceSet['fields']));
583 }
584
585 /**
586 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
587 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
588 * @param array $priceSet
589 *
590 * @throws CRM_Core_Exception
591 * @return int
592 */
00be9182 593 public static function getOnlyPriceFieldValueID(array $priceSet) {
85020e43
EM
594 $priceFieldID = self::getOnlyPriceFieldID($priceSet);
595 if(count($priceSet['fields'][$priceFieldID]['options']) > 1) {
596 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
597 }
598 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
599 }
600
601
ffd93213 602 /**
e0c1764e 603 * @param CRM_Core_Form $form
100fef9d 604 * @param int $id
ffd93213
EM
605 * @param string $entityTable
606 * @param bool $validOnly
100fef9d 607 * @param int $priceSetId
ffd93213
EM
608 *
609 * @return bool|false|int|null
610 */
00be9182 611 public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
6a488035
TO
612 if (!$priceSetId) {
613 $priceSetId = self::getFor($entityTable, $id);
614 }
615
616 //check if priceset is is_config
617 if (is_numeric($priceSetId)) {
9da8dc8c 618 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
6a488035
TO
619 $form->assign('quickConfig', 1);
620 }
621 }
622 // get price info
623 if ($priceSetId) {
624 if ($form->_action & CRM_Core_Action::UPDATE) {
625 $entityId = $entity = NULL;
626
627 switch ($entityTable) {
628 case 'civicrm_event':
629 $entity = 'participant';
630 if (CRM_Utils_System::getClassName($form) == 'CRM_Event_Form_Participant') {
631 $entityId = $form->_id;
632 }
633 else {
634 $entityId = $form->_participantId;
635 }
636 break;
637
638 case 'civicrm_contribution_page':
639 case 'civicrm_contribution':
640 $entity = 'contribution';
641 $entityId = $form->_id;
642 break;
643 }
644
645 if ($entityId && $entity) {
646 $form->_values['line_items'] = CRM_Price_BAO_LineItem::getLineItems($entityId, $entity);
647 }
648 $required = FALSE;
649 }
650 else {
651 $required = TRUE;
652 }
653
654 $form->_priceSetId = $priceSetId;
655 $priceSet = self::getSetDetail($priceSetId, $required, $validOnly);
656 $form->_priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
657 $form->_values['fee'] = CRM_Utils_Array::value('fields', $form->_priceSet);
658
659 //get the price set fields participant count.
660 if ($entityTable == 'civicrm_event') {
661 //get option count info.
662 $form->_priceSet['optionsCountTotal'] = self::getPricesetCount($priceSetId);
663 if ($form->_priceSet['optionsCountTotal']) {
664 $optionsCountDeails = array();
665 if (!empty($form->_priceSet['fields'])) {
666 foreach ($form->_priceSet['fields'] as $field) {
667 foreach ($field['options'] as $option) {
668 $count = CRM_Utils_Array::value('count', $option, 0);
669 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
670 }
671 }
672 }
673 $form->_priceSet['optionsCountDetails'] = $optionsCountDeails;
674 }
675
676 //get option max value info.
677 $optionsMaxValueTotal = 0;
678 $optionsMaxValueDetails = array();
679
680 if (!empty($form->_priceSet['fields'])) {
681 foreach ($form->_priceSet['fields'] as $field) {
682 foreach ($field['options'] as $option) {
683 $maxVal = CRM_Utils_Array::value('max_value', $option, 0);
684 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
685 $optionsMaxValueTotal += $maxVal;
686 }
687 }
688 }
689
690 $form->_priceSet['optionsMaxValueTotal'] = $optionsMaxValueTotal;
691 if ($optionsMaxValueTotal) {
692 $form->_priceSet['optionsMaxValueDetails'] = $optionsMaxValueDetails;
693 }
694 }
695 $form->set('priceSetId', $form->_priceSetId);
696 $form->set('priceSet', $form->_priceSet);
697
698 return $priceSetId;
699 }
700 return FALSE;
701 }
702
ffd93213
EM
703 /**
704 * @param $fields
c490a46a 705 * @param array $params
ffd93213
EM
706 * @param $lineItem
707 * @param string $component
708 */
00be9182 709 public static function processAmount(&$fields, &$params, &$lineItem, $component = '') {
6a488035 710 // using price set
dc428161 711 $totalPrice = $totalTax = 0;
6a488035
TO
712 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
713 if ($component) {
714 $autoRenew = array();
715 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
716 }
717 foreach ($fields as $id => $field) {
a7488080 718 if (empty($params["price_{$id}"]) ||
6a488035
TO
719 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
720 ) {
721 // skip if nothing was submitted for this field
722 continue;
723 }
724
725 switch ($field['html_type']) {
726 case 'Text':
be45c8b4
EM
727 $firstOption = reset($field['options']);
728 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
6a488035 729 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
dc428161 730 if (CRM_Utils_Array::value('tax_rate', $field['options'][key($field['options'])])) {
731 $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
732 $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
733 }
049db839 734 if (CRM_Utils_Array::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
735 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
736 if (array_key_exists($params['financial_type_id'], $taxRates)) {
737 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
738 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
cce6ec9f 739 $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
049db839 740 $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
741 $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
742 }
743 }
3b5db8ce 744 $totalPrice += $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[key($field['options'])]);
6a488035
TO
745 break;
746
747 case 'Radio':
748 //special case if user select -none-
749 if ($params["price_{$id}"] <= 0) {
750 continue;
751 }
752 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
753 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
754 $optionLabel = CRM_Utils_Array::value('label', $field['options'][$optionValueId]);
755 $params['amount_priceset_level_radio'] = array();
756 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
757 if (isset($radioLevel)) {
758 $radioLevel = array_merge($radioLevel,
759 array_keys($params['amount_priceset_level_radio'])
760 );
761 }
762 else {
763 $radioLevel = array_keys($params['amount_priceset_level_radio']);
764 }
765 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
dc428161 766 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
767 $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
768 $totalTax += $field['options'][$optionValueId]['tax_amount'];
c40e1ff4 769 if (CRM_Utils_Array::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
770 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
771 }
dc428161 772 }
c40e1ff4 773 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
cde484fd
DL
774 if (
775 $component &&
a6c4ca20 776 // auto_renew exists and is empty in some workflows, which php treat as a 0
28156120 777 // and hence we explicitly check to see if auto_renew is numeric
cde484fd
DL
778 isset($lineItem[$optionValueId]['auto_renew']) &&
779 is_numeric($lineItem[$optionValueId]['auto_renew'])
780 ) {
6a488035
TO
781 $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
782 }
783 break;
784
785 case 'Select':
786 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
787 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
788 $optionLabel = $field['options'][$optionValueId]['label'];
789 $params['amount_priceset_level_select'] = array();
790 $params['amount_priceset_level_select'][CRM_Utils_Array::key(1, $params["price_{$id}"])] = $optionLabel;
791 if (isset($selectLevel)) {
792 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
793 }
794 else {
795 $selectLevel = array_keys($params['amount_priceset_level_select']);
796 }
797 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
dc428161 798 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
799 $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
800 $totalTax += $field['options'][$optionValueId]['tax_amount'];
801 }
c40e1ff4 802 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
cde484fd
DL
803 if (
804 $component &&
805 isset($lineItem[$optionValueId]['auto_renew']) &&
806 is_numeric($lineItem[$optionValueId]['auto_renew'])
807 ) {
6a488035
TO
808 $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
809 }
810 break;
811
812 case 'CheckBox':
813 $params['amount_priceset_level_checkbox'] = $optionIds = array();
814 foreach ($params["price_{$id}"] as $optionId => $option) {
815 $optionIds[] = $optionId;
816 $optionLabel = $field['options'][$optionId]['label'];
817 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
818 if (isset($checkboxLevel)) {
819 $checkboxLevel = array_unique(array_merge(
820 $checkboxLevel,
821 array_keys($params['amount_priceset_level_checkbox'])
822 )
823 );
824 }
825 else {
826 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
827 }
828 }
829 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
830 foreach ($optionIds as $optionId) {
dc428161 831 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionId])) {
832 $lineItem = self::setLineItem($field, $lineItem, $optionId);
833 $totalTax += $field['options'][$optionId]['tax_amount'];
834 }
c40e1ff4 835 $totalPrice += $lineItem[$optionId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionId]);
cde484fd
DL
836 if (
837 $component &&
838 isset($lineItem[$optionId]['auto_renew']) &&
839 is_numeric($lineItem[$optionId]['auto_renew'])
840 ) {
6a488035
TO
841 $autoRenew[$lineItem[$optionId]['auto_renew']] += $lineItem[$optionId]['line_total'];
842 }
843 }
844 break;
845 }
846 }
847
848 $amount_level = array();
849 $totalParticipant = 0;
850 if (is_array($lineItem)) {
851 foreach ($lineItem as $values) {
852 $totalParticipant += $values['participant_count'];
853 if ($values['html_type'] == 'Text') {
854 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
855 continue;
856 }
857 $amount_level[] = $values['label'];
858 }
859 }
860
861 $displayParticipantCount = '';
862 if ($totalParticipant > 0) {
863 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
864 }
865 $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
866 $params['amount'] = $totalPrice;
dc428161 867 $params['tax_amount'] = $totalTax;
6a488035
TO
868 if ($component) {
869 foreach ($autoRenew as $dontCare => $eachAmount) {
870 if (!$eachAmount) {
cde484fd 871 unset($autoRenew[$dontCare]);
6a488035
TO
872 }
873 }
874 if (count($autoRenew) > 1 ) {
875 $params['autoRenew'] = $autoRenew;
876 }
877 }
878 }
879
880 /**
100fef9d 881 * Build the price set form.
6a488035 882 *
e0c1764e 883 * @param CRM_Core_Form $form
dd244018 884 *
355ba699 885 * @return void
6a488035 886 */
00be9182 887 public static function buildPriceSet(&$form) {
6a488035 888 $priceSetId = $form->get('priceSetId');
6a488035
TO
889 if (!$priceSetId) {
890 return;
891 }
892
893 $validFieldsOnly = TRUE;
894 $className = CRM_Utils_System::getClassName($form);
895 if (in_array($className, array(
896 'CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'))) {
897 $validFieldsOnly = FALSE;
898 }
899
900 $priceSet = self::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
901 $form->_priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
883e4763 902 $validPriceFieldIds = array_keys($form->_priceSet['fields']);
6a488035 903 $form->_quickConfig = $quickConfig = 0;
9da8dc8c 904 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
6a488035
TO
905 $quickConfig = 1;
906 }
907
908 $form->assign('quickConfig', $quickConfig);
909 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
910 $form->_quickConfig = $quickConfig;
911 }
912 $form->assign('priceSet', $form->_priceSet);
913
914 $component = 'contribution';
915 if ($className == 'CRM_Member_Form_Membership') {
916 $component = 'membership';
917 }
918
919 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
920 $feeBlock = &$form->_values['fee'];
921 if (!empty($form->_useForMember)) {
922 $component = 'membership';
923 }
924 }
925 else {
926 $feeBlock = &$form->_priceSet['fields'];
927 }
928
929 // call the hook.
930 CRM_Utils_Hook::buildAmount($component, $form, $feeBlock);
931
c7b3d063
DG
932 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
933 $adminFieldVisible = false;
934 if (CRM_Core_Permission::check('administer CiviCRM')) {
77b97be7 935 $adminFieldVisible = true;
c7b3d063 936 }
77b97be7 937
883e4763 938 foreach ($feeBlock as $id => $field) {
6a488035 939 if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
c7b3d063 940 (CRM_Utils_Array::value('visibility', $field) == 'admin' && $adminFieldVisible == true) ||
6a488035
TO
941 !$validFieldsOnly
942 ) {
943 $options = CRM_Utils_Array::value('options', $field);
944 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
cc509891 945 $userid = $form->getVar('_membershipContactID');
6a488035
TO
946 $checklifetime = self::checkCurrentMembership($options, $userid);
947 if ($checklifetime) {
948 $form->assign('ispricelifetime', TRUE);
949 }
950 }
883e4763 951 if (!is_array($options) || !in_array($id, $validPriceFieldIds)) {
6a488035
TO
952 continue;
953 }
9da8dc8c 954 CRM_Price_BAO_PriceField::addQuickFormElement($form,
6a488035
TO
955 'price_' . $field['id'],
956 $field['id'],
957 FALSE,
958 CRM_Utils_Array::value('is_required', $field, FALSE),
959 NULL,
960 $options
961 );
962 }
963 }
964 }
965
966 /**
100fef9d 967 * Check the current Membership
6a488035
TO
968 * having end date null.
969 */
00be9182 970 public static function checkCurrentMembership(&$options, $userid) {
6a488035
TO
971 if (!$userid || empty($options)) {
972 return;
973 }
974 static $_contact_memberships = array();
975 $checklifetime = FALSE;
976 foreach ($options as $key => $value) {
a7488080 977 if (!empty($value['membership_type_id'])) {
6a488035
TO
978 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
979 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership::getContactMembership($userid, $value['membership_type_id'], FALSE);
980 }
981 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
8cc574cf 982 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
6a488035
TO
983 unset($options[$key]);
984 $checklifetime = TRUE;
985 }
986 }
987 }
988 if ($checklifetime) {
989 return TRUE;
990 }
991 else {
992 return FALSE;
993 }
994 }
995
996 /**
100fef9d 997 * Set daefult the price set fields.
6a488035 998 *
c490a46a 999 * @param CRM_Core_Form $form
fd31fa4c
EM
1000 * @param $defaults
1001 *
6a488035 1002 * @return array $defaults
6a488035 1003 */
00be9182 1004 public static function setDefaultPriceSet(&$form, &$defaults) {
6a488035
TO
1005 if (!isset($form->_priceSet) || empty($form->_priceSet['fields'])) {
1006 return $defaults;
1007 }
1008
1009 foreach ($form->_priceSet['fields'] as $key => $val) {
1010 foreach ($val['options'] as $keys => $values) {
1011 if ($values['is_default']) {
1012 if ($val['html_type'] == 'CheckBox') {
1013 $defaults["price_{$key}"][$keys] = 1;
1014 }
1015 else {
1016 $defaults["price_{$key}"] = $keys;
1017 }
1018 }
1019 }
1020 }
1021 return $defaults;
1022 }
1023
b2cdd843
EM
1024 /**
1025 * Supports event create function by setting up required price sets, not tested but expect
1026 * it will work for contribution page
1027 * @param array $params as passed to api/bao create fn
1028 * @param CRM_Core_DAO $entity object for given entity
1029 * @param string $entityName name of entity - e.g event
1030 */
00be9182 1031 public static function setPriceSets(&$params, $entity, $entityName) {
b2cdd843
EM
1032 if(empty($params['price_set_id']) || !is_array($params['price_set_id'])) {
1033 return;
1034 }
1035 // CRM-14069 note that we may as well start by assuming more than one.
1036 // currently the form does not pass in as an array & will be skipped
1037 // test is passing in as an array but I feel the api should have a metadata that allows
1038 // transform of single to array - seems good for managing transitions - in which case all api
1039 // calls that set price_set_id will hit this
1040 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1041 // all separated values, strings, json half-separated values (in participant we hit this)
1042 // to be converted to json @ api layer
1043 $pse = new CRM_Price_DAO_PriceSetEntity();
1044 $pse->entity_table = 'civicrm_' . $entityName;
1045 $pse->entity_id = $entity->id;
1046 while ($pse->fetch()) {
1047 if(!in_array($pse->price_set_id, $params['price_set_id'])) {
1048 // note an even more aggressive form of this deletion currently happens in event form
1049 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1050 // on the participant record
1051 if (CRM_Price_BAO_PriceSet::removeFrom('civicrm_' . $entityName, $entity->id)) {
07102c2c 1052 CRM_Core_BAO_Discount::del($entity->id,'civicrm_' . $entityName);
b2cdd843
EM
1053 }
1054 }
1055 }
1056 foreach ($params['price_set_id'] as $priceSetID) {
1057 CRM_Price_BAO_PriceSet::addTo('civicrm_' . $entityName, $entity->id, $priceSetID);
1058 //@todo - how should we do this - copied from form
1059 //if (CRM_Utils_Array::value('price_field_id', $params)) {
1060 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1061 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1062 //}
1063 }
1064 }
6a488035
TO
1065 /**
1066 * Get field ids of a price set
1067 *
e0c1764e 1068 * @param int $id Price Set id
6a488035
TO
1069 *
1070 * @return array of the field ids
1071 *
6a488035
TO
1072 * @static
1073 */
1074 public static function getFieldIds($id) {
9da8dc8c 1075 $priceField = new CRM_Price_DAO_PriceField();
6a488035
TO
1076 $priceField->price_set_id = $id;
1077 $priceField->find();
1078 while ($priceField->fetch()) {
1079 $var[] = $priceField->id;
1080 }
1081 return $var;
1082 }
1083
1084 /**
1085 * This function is to make a copy of a price set, including
1086 * all the fields
1087 *
1088 * @param int $id the price set id to copy
1089 *
1090 * @return the copy object
6a488035
TO
1091 * @static
1092 */
00be9182 1093 public static function copy($id) {
6a488035
TO
1094 $maxId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1095
1096 $title = ts('[Copy id %1]', array(1 => $maxId + 1));
1097 $fieldsFix = array(
1098 'suffix' => array('title' => ' ' . $title,
1099 'name' => '__Copy_id_' . ($maxId + 1) . '_',
1100 ),
1101 );
1102
9da8dc8c 1103 $copy = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSet',
6a488035
TO
1104 array('id' => $id),
1105 NULL,
1106 $fieldsFix
1107 );
1108
1109 //copying all the blocks pertaining to the price set
9da8dc8c 1110 $copyPriceField = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceField',
6a488035
TO
1111 array('price_set_id' => $id),
1112 array('price_set_id' => $copy->id)
1113 );
1114 if (!empty($copyPriceField)) {
1115 $price = array_combine(self::getFieldIds($id), self::getFieldIds($copy->id));
1116
1117 //copy option group and values
1118 foreach ($price as $originalId => $copyId) {
9da8dc8c 1119 CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceFieldValue',
6a488035
TO
1120 array('price_field_id' => $originalId),
1121 array('price_field_id' => $copyId)
1122 );
1123 }
1124 }
1125 $copy->save();
1126
1127 CRM_Utils_Hook::copy('Set', $copy);
1128 return $copy;
1129 }
1130
1131 /**
1132 * This function is to check price set permission
1133 *
1134 * @param int $sid the price set id
77b97be7
EM
1135 *
1136 * @return bool
6a488035 1137 */
00be9182 1138 public static function checkPermission($sid) {
44c8822b 1139 if ($sid && self::eventPriceSetDomainID()) {
9da8dc8c 1140 $domain_id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
6a488035 1141 if (CRM_Core_Config::domainID() != $domain_id) {
0499b0ad 1142 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
6a488035
TO
1143 }
1144 }
1145 return TRUE;
1146 }
1147
1148 /**
1149 * Get the sum of participant count
1150 * for all fields of given price set.
1151 *
1152 * @param int $sid the price set id
1153 *
77b97be7
EM
1154 * @param bool $onlyActive
1155 *
1156 * @return int|null|string
6a488035
TO
1157 * @static
1158 */
1159 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1160 $count = 0;
1161 if (!$sid) {
1162 return $count;
1163 }
1164
1165 $where = NULL;
1166 if ($onlyActive) {
1167 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1168 }
1169
1170 static $pricesetFieldCount = array();
1171 if (!isset($pricesetFieldCount[$sid])) {
1172 $sql = "
1173 SELECT sum(value.count) as totalCount
1174 FROM civicrm_price_field_value value
1175INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1176INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1177 WHERE pset.id = %1
1178 $where";
1179
1180 $count = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1181 $pricesetFieldCount[$sid] = ($count) ? $count : 0;
1182 }
1183
1184 return $pricesetFieldCount[$sid];
1185 }
1186
ffd93213
EM
1187 /**
1188 * @param $ids
1189 *
1190 * @return array
1191 */
6a488035
TO
1192 public static function getMembershipCount($ids) {
1193 $queryString = "
1194SELECT count( pfv.id ) AS count, pfv.id AS id
1195FROM civicrm_price_field_value pfv
1196INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1197WHERE pfv.id IN ( $ids )
1198GROUP BY mt.member_of_contact_id";
1199
1200 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
1201 $count = array();
1202
1203 while ($crmDAO->fetch()) {
1204 $count[$crmDAO->id] = $crmDAO->count;
1205 }
1206
1207 return $count;
1208 }
1209
1210 /**
100fef9d 1211 * Check if auto renew option should be shown
6a488035
TO
1212 *
1213 * @param int $priceSetId price set id
1214 *
1215 * @return int $autoRenewOption ( 0:hide, 1:optional 2:required )
1216 */
1217 public static function checkAutoRenewForPriceSet($priceSetId) {
1218 // auto-renew option should be visible if membership types associated with all the fields has
1219 // been set for auto-renew option
1220 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1221
1222 // get the membership type auto renew option and check if required or optional
1223 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1224 FROM civicrm_price_field_value pfv
1225 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1226 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1227 WHERE pf.price_set_id = %1
1228 AND pf.is_active = 1
1229 AND pfv.is_active = 1';
1230
1231 $params = array(1 => array($priceSetId, 'Integer'));
1232
1233 $dao = CRM_Core_DAO::executeQuery($query, $params);
1234 $autoRenewOption = 2;
1235 $interval = $unit = array();
1236 while ($dao->fetch()) {
1237 if (!$dao->auto_renew) {
1238 $autoRenewOption = 0;
1239 break;
1240 }
1241 if ($dao->auto_renew == 1) {
1242 $autoRenewOption = 1;
1243 }
1244
1245 $interval[$dao->duration_interval] = $dao->duration_interval;
1246 $unit[$dao->duration_unit] = $dao->duration_unit;
1247 }
1248
1249 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1250 return $autoRenewOption;
1251 }
1252 else {
1253 return 0;
1254 }
1255 }
1256
1257 /**
100fef9d 1258 * Retrieve auto renew frequency and interval
6a488035
TO
1259 *
1260 * @param int $priceSetId price set id
1261 *
1262 * @return array associate array of frequency interval and unit
1263 * @static
6a488035
TO
1264 */
1265 public static function getRecurDetails($priceSetId) {
1266 $query = 'SELECT mt.duration_interval, mt.duration_unit
1267 FROM civicrm_price_field_value pfv
1268 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1269 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1270 WHERE pf.price_set_id = %1 LIMIT 1';
1271
1272 $params = array(1 => array($priceSetId, 'Integer'));
1273 $dao = CRM_Core_DAO::executeQuery($query, $params);
1274 $dao->fetch();
1275 return array($dao->duration_interval, $dao->duration_unit);
1276 }
1277
ffd93213
EM
1278 /**
1279 * @return object
1280 */
00be9182 1281 public static function eventPriceSetDomainID() {
6a488035
TO
1282 return CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME,
1283 'event_price_set_domain_id',
1284 NULL, FALSE
1285 );
1286 }
1287
1288 /**
100fef9d 1289 * Update the is_quick_config flag in the db
6a488035
TO
1290 *
1291 * @param int $id id of the database record
1292 * @param boolean $isQuickConfig value we want to set the is_quick_config field
1293 *
1294 * @return Object DAO object on sucess, null otherwise
1295 * @static
6a488035 1296 */
00be9182 1297 public static function setIsQuickConfig($id, $isQuickConfig) {
9da8dc8c 1298 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
6a488035
TO
1299 }
1300
1301 /**
cde484fd 1302 * Check if price set id provides option for
6a488035
TO
1303 * user to select both auto-renew and non-auto-renew memberships
1304 *
6a488035
TO
1305 * @static
1306 *
1307 */
1308 public static function checkMembershipPriceSet($id) {
cde484fd 1309 $query =
6a488035
TO
1310"
1311SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1312FROM civicrm_price_field_value pfv
1313LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1314LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1315LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1316WHERE ps.id = %1
1317";
1318
1319 $params = array(1 => array($id, 'Integer'));
1320 $dao = CRM_Core_DAO::executeQuery($query, $params);
1321
1322 $autoRenew = array();
1323 //FIXME: do a comprehensive check of whether
1324 //2 membership types can be selected
1325 //instead of comparing all of them
1326 while ($dao->fetch()) {
cde484fd 1327 //temp fix for #CRM-10370
6a488035
TO
1328 //if its NULL consider it '0' i.e. 'No auto-renew option'
1329 $daoAutoRenew = $dao->auto_renew;
1330 if ($daoAutoRenew === NULL) {
1331 $daoAutoRenew = 0;
1332 }
1333 if (!empty($autoRenew) && !in_array($daoAutoRenew, $autoRenew)) {
1334 return true;
1335 }
1336 $autoRenew[] = $daoAutoRenew;
1337 }
1338 return false;
1339 }
1340
e0c1764e 1341 /**
c6914066
PN
1342 * Copy priceSet when event/contibution page is copied
1343 *
c490a46a
CW
1344 * @param string $baoName BAO name
1345 * @param int $id old event/contribution page id
1346 * @param int $newId newly created event/contribution page id
c6914066 1347 */
00be9182 1348 public static function copyPriceSet($baoName, $id, $newId) {
9da8dc8c 1349 $priceSetId = CRM_Price_BAO_PriceSet::getFor($baoName, $id);
c6914066 1350 if ($priceSetId) {
9da8dc8c 1351 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
c6914066 1352 if($isQuickConfig) {
9da8dc8c 1353 $copyPriceSet = &CRM_Price_BAO_PriceSet::copy($priceSetId);
1354 CRM_Price_BAO_PriceSet::addTo($baoName, $newId, $copyPriceSet->id);
44c8822b 1355 }
c6914066 1356 else {
9da8dc8c 1357 $copyPriceSet = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSetEntity',
c6914066
PN
1358 array(
1359 'entity_id' => $id,
1360 'entity_table' => $baoName,
1361 ),
1362 array('entity_id' => $newId)
1363 );
1364 }
1365 // copy event discount
1366 if ($baoName == 'civicrm_event') {
1367 $discount = CRM_Core_BAO_Discount::getOptionGroup($id, 'civicrm_event');
1368 foreach ($discount as $discountId => $setId) {
1369
9da8dc8c 1370 $copyPriceSet = &CRM_Price_BAO_PriceSet::copy($setId);
44c8822b 1371
28156120 1372 CRM_Core_DAO::copyGeneric(
c6914066
PN
1373 'CRM_Core_DAO_Discount',
1374 array(
1375 'id' => $discountId,
1376 ),
1377 array(
1378 'entity_id' => $newId,
1379 'price_set_id' => $copyPriceSet->id,
1380 )
1381 );
1382 }
1383 }
1384 }
1385 }
dc428161 1386
1387 /*
1388 * Function to set tax_amount and tax_rate in LineItem
1389 *
1390 *
1391 */
00be9182 1392 public static function setLineItem($field, $lineItem, $optionValueId) {
dc428161 1393 if ($field['html_type'] == 'Text') {
1394 $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
1395 }
1396 else {
1397 $taxAmount = $field['options'][$optionValueId]['tax_amount'];
1398 }
1399 $taxRate = $field['options'][$optionValueId]['tax_rate'];
dc428161 1400 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1401 $lineItem[$optionValueId]['tax_rate'] = $taxRate;
1402
1403 return $lineItem;
1404 }
6a488035 1405}