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