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