7dfdd90ef188fc247db18893499d6b48090cf3af
[civicrm-core.git] / CRM / Upgrade / Snapshot / V4p2 / Price / BAO / Set.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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
31 * @copyright CiviCRM LLC (c) 2004-2015
32 */
33
34 /**
35 * Business object for managing price sets.
36 */
37 class CRM_Upgrade_Snapshot_V4p2_Price_BAO_Set extends CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set {
38
39 /**
40 * Class constructor.
41 */
42 public function __construct() {
43 parent::__construct();
44 }
45
46 /**
47 * Takes an associative array and creates a price set object.
48 *
49 * @param array $params
50 * (reference) an assoc array of name/value pairs.
51 *
52 * @return CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set
53 */
54 public static function create(&$params) {
55 $priceSetBAO = new CRM_Upgrade_Snapshot_V4p2_Price_BAO_Set();
56 $priceSetBAO->copyValues($params);
57 if (self::eventPriceSetDomainID()) {
58 $priceSetBAO->domain_id = CRM_Core_Config::domainID();
59 }
60 return $priceSetBAO->save();
61 }
62
63 /**
64 * Fetch object based on array of properties.
65 *
66 * @param array $params
67 * (reference ) an assoc array of name/value pairs.
68 * @param array $defaults
69 * (reference ) an assoc array to hold the flattened values.
70 *
71 * @return CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set
72 */
73 public static function retrieve(&$params, &$defaults) {
74 return CRM_Core_DAO::commonRetrieve('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set', $params, $defaults);
75 }
76
77 /**
78 * Update the is_active flag in the db.
79 *
80 * @param int $id
81 * Id of the database record.
82 * @param bool $isActive
83 * Value we want to set the is_active field.
84 *
85 * @return Object
86 * DAO object on success, null otherwise
87 */
88 public static function setIsActive($id, $isActive) {
89 return CRM_Core_DAO::setFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set', $id, 'is_active', $isActive);
90 }
91
92 /**
93 * Calculate the default price set id assigned to the contribution/membership etc.
94 *
95 * @param string $entity
96 *
97 * @return int
98 * priceSetID
99 */
100 public static function getDefaultPriceSet($entity = 'contribution') {
101 if ($entity == 'contribution') {
102 $entityName = 'default_contribution_amount';
103 }
104 elseif ($entity == 'membership') {
105 $entityName = 'default_membership_type_amount';
106 }
107
108 $sql = "
109 SELECT ps.id AS setID, pfv.price_field_id AS priceFieldID, pfv.id AS priceFieldValueID, pfv.name, pfv.label
110 FROM civicrm_price_set ps
111 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
112 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
113 WHERE ps.name = '{$entityName}'
114 ";
115
116 $dao = CRM_Core_DAO::executeQuery($sql);
117 $defaultPriceSet = array();
118 while ($dao->fetch()) {
119 $defaultPriceSet[$dao->priceFieldValueID]['setID'] = $dao->setID;
120 $defaultPriceSet[$dao->priceFieldValueID]['priceFieldID'] = $dao->priceFieldID;
121 $defaultPriceSet[$dao->priceFieldValueID]['name'] = $dao->name;
122 $defaultPriceSet[$dao->priceFieldValueID]['label'] = $dao->label;
123 }
124
125 return $defaultPriceSet;
126 }
127
128 /**
129 * Get the price set title.
130 *
131 * @param int $id
132 * Id of price set.
133 *
134 * @return string
135 * title
136 */
137 public static function getTitle($id) {
138 return CRM_Core_DAO::getFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set', $id, 'title');
139 }
140
141 /**
142 * Return a list of all forms which use this price set.
143 *
144 * @param int $id
145 * Id of price set.
146 * @param bool|\str $simpleReturn - get raw data. Possible values: 'entity', 'table'
147 *
148 * @return array
149 */
150 public static function &getUsedBy($id, $simpleReturn = FALSE) {
151 $usedBy = $forms = $tables = array();
152 $queryString = "
153 SELECT entity_table, entity_id
154 FROM civicrm_price_set_entity
155 WHERE price_set_id = %1";
156 $params = array(1 => array($id, 'Integer'));
157 $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
158
159 while ($crmFormDAO->fetch()) {
160 $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
161 $tables[] = $crmFormDAO->entity_table;
162 }
163 // Return only tables
164 if ($simpleReturn == 'table') {
165 return $tables;
166 }
167 if (empty($forms)) {
168 $queryString = "
169 SELECT cli.entity_table, cli.entity_id
170 FROM civicrm_line_item cli
171 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
172 WHERE cpf.price_set_id = %1";
173 $params = array(1 => array($id, 'Integer'));
174 $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
175 while ($crmFormDAO->fetch()) {
176 $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
177 $tables[] = $crmFormDAO->entity_table;
178 }
179 if (empty($forms)) {
180 return $usedBy;
181 }
182 }
183 // Return only entity data
184 if ($simpleReturn == 'entity') {
185 return $forms;
186 }
187 foreach ($forms as $table => $entities) {
188 switch ($table) {
189 case 'civicrm_event':
190 $ids = implode(',', $entities);
191 $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
192 FROM civicrm_event ce
193 LEFT JOIN civicrm_option_value ON
194 ( ce.event_type_id = civicrm_option_value.value )
195 LEFT JOIN civicrm_option_group ON
196 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
197 WHERE
198 civicrm_option_group.name = 'event_type' AND
199 ( ce.is_template IS NULL OR ce.is_template = 0) AND
200 ce.id IN ($ids) AND
201 ce.is_active = 1;";
202 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
203 while ($crmDAO->fetch()) {
204 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
205 $usedBy[$table][$crmDAO->id]['eventType'] = $crmDAO->eventType;
206 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
207 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
208 $usedBy[$table][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
209 }
210 break;
211
212 case 'civicrm_contribution_page':
213 $ids = implode(',', $entities);
214 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
215 FROM civicrm_contribution_page cp, civicrm_contribution_type ct
216 WHERE ct.id = cp.contribution_type_id AND
217 cp.id IN ($ids) AND
218 cp.is_active = 1;";
219 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
220 while ($crmDAO->fetch()) {
221 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
222 $usedBy[$table][$crmDAO->id]['type'] = $crmDAO->type;
223 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
224 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
225 }
226 break;
227
228 case 'civicrm_contribution':
229 case 'civicrm_membership':
230 case 'civicrm_participant':
231 $usedBy[$table] = 1;
232 break;
233
234 default:
235 CRM_Core_Error::fatal("$table is not supported in PriceSet::usedBy()");
236 break;
237 }
238 }
239
240 return $usedBy;
241 }
242
243 /**
244 * Delete the price set.
245 *
246 * @param int $id
247 * Price Set id.
248 *
249 * @return bool
250 * false if fields exist for this set, true if the
251 * set could be deleted
252 */
253 public static function deleteSet($id) {
254 // remove from all inactive forms
255 $usedBy = self::getUsedBy($id);
256 if (isset($usedBy['civicrm_event'])) {
257 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
258 $eventDAO = new CRM_Event_DAO_Event();
259 $eventDAO->id = $eventId;
260 $eventDAO->find();
261 while ($eventDAO->fetch()) {
262 self::removeFrom('civicrm_event', $eventDAO->id);
263 }
264 }
265 }
266
267 // delete price fields
268 $priceField = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field();
269 $priceField->price_set_id = $id;
270 $priceField->find();
271 while ($priceField->fetch()) {
272 // delete options first
273 CRM_Upgrade_Snapshot_V4p2_Price_BAO_Field::deleteField($priceField->id);
274 }
275
276 $set = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set();
277 $set->id = $id;
278 return $set->delete();
279 }
280
281 /**
282 * Link the price set with the specified table and id.
283 *
284 * @param string $entityTable
285 * @param int $entityId
286 * @param int $priceSetId
287 *
288 * @return bool
289 */
290 public static function addTo($entityTable, $entityId, $priceSetId) {
291 // verify that the price set exists
292 $dao = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set();
293 $dao->id = $priceSetId;
294 if (!$dao->find()) {
295 return FALSE;
296 }
297 unset($dao);
298
299 $dao = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_SetEntity();
300 // find if this already exists
301 $dao->entity_id = $entityId;
302 $dao->entity_table = $entityTable;
303 $dao->find(TRUE);
304
305 // add or update price_set_id
306 $dao->price_set_id = $priceSetId;
307 return $dao->save();
308 }
309
310 /**
311 * Delete price set for the given entity and id.
312 *
313 * @param string $entityTable
314 * @param int $entityId
315 *
316 * @return mixed
317 */
318 public static function removeFrom($entityTable, $entityId) {
319 $dao = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_SetEntity();
320 $dao->entity_table = $entityTable;
321 $dao->entity_id = $entityId;
322 return $dao->delete();
323 }
324
325 /**
326 * Find a price_set_id associated with the given details.
327 *
328 * Used For value for events:1, contribution:2, membership:3
329 *
330 * @param string $entityTable
331 * @param int $entityId
332 * @param int $usedFor
333 * ( price set that extends/used for particular component ).
334 *
335 * @param null $isQuickConfig
336 * @param null $setName
337 *
338 * @return int|false
339 * price_set_id, or false if none found
340 */
341 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
342 if (!$entityTable || !$entityId) {
343 return FALSE;
344 }
345
346 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
347 FROM civicrm_price_set ps
348 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
349 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
350 if ($isQuickConfig) {
351 $sql .= " AND ps.is_quick_config = 0 ";
352 }
353 $params = array(
354 1 => array($entityTable, 'String'),
355 2 => array($entityId, 'Integer'),
356 );
357 if ($usedFor) {
358 $sql .= " AND ps.extends LIKE '%%3%' ";
359 $params[3] = array($usedFor, 'Integer');
360 }
361
362 $dao = CRM_Core_DAO::executeQuery($sql, $params);
363 $dao->fetch();
364 $setName = (isset($dao->price_set_name)) ? $dao->price_set_name : FALSE;
365 return (isset($dao->price_set_id)) ? $dao->price_set_id : FALSE;
366 }
367
368 /**
369 * Find a price_set_id associatied with the given option value or field ID.
370 *
371 * @param array $params
372 * (reference) an assoc array of name/value pairs.
373 * array may contain either option id or
374 * price field id
375 *
376 * @return int|null
377 * price set id on success, null otherwise
378 */
379 public static function getSetId(&$params) {
380 $fid = NULL;
381
382 if ($oid = CRM_Utils_Array::value('oid', $params)) {
383 $fieldValue = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_FieldValue();
384 $fieldValue->id = $oid;
385 if ($fieldValue->find(TRUE)) {
386 $fid = $fieldValue->price_field_id;
387 }
388 }
389 else {
390 $fid = CRM_Utils_Array::value('fid', $params);
391 }
392
393 if (isset($fid)) {
394 return CRM_Core_DAO::getFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field', $fid, 'price_set_id');
395 }
396
397 return NULL;
398 }
399
400 /**
401 * Return an associative array of all price sets.
402 *
403 * @param bool $withInactive
404 * Whether or not to include inactive entries.
405 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
406 *
407 * @return array
408 * associative array of id => name
409 */
410 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE) {
411 $query = "
412 SELECT
413 DISTINCT ( price_set_id ) as id, title
414 FROM
415 civicrm_price_field,
416 civicrm_price_set
417 WHERE
418 civicrm_price_set.id = civicrm_price_field.price_set_id AND is_quick_config = 0 ";
419
420 if (!$withInactive) {
421 $query .= " AND civicrm_price_set.is_active = 1 ";
422 }
423
424 if (self::eventPriceSetDomainID()) {
425 $query .= " AND civicrm_price_set.domain_id = " . CRM_Core_Config::domainID();
426 }
427
428 $priceSets = array();
429
430 if ($extendComponentName) {
431 $componentId = CRM_Core_Component::getComponentID($extendComponentName);
432 if (!$componentId) {
433 return $priceSets;
434 }
435 $query .= " AND civicrm_price_set.extends LIKE '%$componentId%' ";
436 }
437
438 $dao = CRM_Core_DAO::executeQuery($query);
439 while ($dao->fetch()) {
440 $priceSets[$dao->id] = $dao->title;
441 }
442 return $priceSets;
443 }
444
445 /**
446 * Get price set details.
447 *
448 * An array containing price set details (including price fields) is returned
449 *
450 * @param int $setID
451 * Price set id whose details are needed.
452 * @param bool $required
453 * @param bool $validOnly
454 *
455 * @return array
456 * array consisting of field details
457 */
458 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
459 // create a new tree
460 $setTree = array();
461 $select = $from = $where = $orderBy = '';
462
463 $priceFields = array(
464 'id',
465 'name',
466 'label',
467 'html_type',
468 'is_enter_qty',
469 'help_pre',
470 'help_post',
471 'weight',
472 'is_display_amounts',
473 'options_per_line',
474 'is_active',
475 'active_on',
476 'expire_on',
477 'javascript',
478 'visibility_id',
479 'is_required',
480 );
481 if ($required == TRUE) {
482 $priceFields[] = 'is_required';
483 }
484
485 // create select
486 $select = 'SELECT ' . implode(',', $priceFields);
487 $from = ' FROM civicrm_price_field';
488
489 $params = array();
490 $params[1] = array($setID, 'Integer');
491 $where = '
492 WHERE price_set_id = %1
493 AND is_active = 1
494 ';
495 $dateSelect = '';
496 if ($validOnly) {
497 $currentTime = date('YmdHis');
498 $dateSelect = "
499 AND ( active_on IS NULL OR active_on <= {$currentTime} )
500 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
501 ";
502 }
503
504 $orderBy = ' ORDER BY weight';
505
506 $sql = $select . $from . $where . $dateSelect . $orderBy;
507
508 $dao = CRM_Core_DAO::executeQuery($sql, $params);
509
510 $visibility = CRM_Core_PseudoConstant::visibility('name');
511 while ($dao->fetch()) {
512 $fieldID = $dao->id;
513
514 $setTree[$setID]['fields'][$fieldID] = array();
515 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
516
517 foreach ($priceFields as $field) {
518 if ($field == 'id' || is_null($dao->$field)) {
519 continue;
520 }
521
522 if ($field == 'visibility_id') {
523 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
524 }
525 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
526 }
527 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Upgrade_Snapshot_V4p2_Price_BAO_Field::getOptions($fieldID, FALSE);
528 }
529
530 // also get the pre and post help from this price set
531 $sql = "
532 SELECT extends, contribution_type_id, help_pre, help_post, is_quick_config
533 FROM civicrm_price_set
534 WHERE id = %1";
535 $dao = CRM_Core_DAO::executeQuery($sql, $params);
536 if ($dao->fetch()) {
537 $setTree[$setID]['extends'] = $dao->extends;
538 $setTree[$setID]['contribution_type_id'] = $dao->contribution_type_id;
539 $setTree[$setID]['help_pre'] = $dao->help_pre;
540 $setTree[$setID]['help_post'] = $dao->help_post;
541 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config;
542 }
543 return $setTree;
544 }
545
546 /**
547 * Initialise set.
548 *
549 * @param CRM_Core_Form $form
550 * @param int $id
551 * @param string $entityTable
552 * @param bool $validOnly
553 * @param int $priceSetId
554 *
555 * @return bool|false|int|null
556 */
557 public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
558 if (!$priceSetId) {
559 $priceSetId = self::getFor($entityTable, $id);
560 }
561
562 //check if priceset is is_config
563 if (is_numeric($priceSetId)) {
564 if (CRM_Core_DAO::getFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
565 $form->assign('quickConfig', 1);
566 }
567 }
568 // get price info
569 if ($priceSetId) {
570 if ($form->_action & CRM_Core_Action::UPDATE) {
571 $entityId = $entity = NULL;
572
573 switch ($entityTable) {
574 case 'civicrm_event':
575 $entity = 'participant';
576 if (CRM_Utils_System::getClassName($form) == 'CRM_Event_Form_Participant') {
577 $entityId = $form->_id;
578 }
579 else {
580 $entityId = $form->_participantId;
581 }
582 break;
583
584 case 'civicrm_contribution_page':
585 case 'civicrm_contribution':
586 $entity = 'contribution';
587 $entityId = $form->_id;
588 break;
589 }
590
591 if ($entityId && $entity) {
592 $form->_values['line_items'] = CRM_Upgrade_Snapshot_V4p2_Price_BAO_LineItem::getLineItems($entityId, $entity);
593 }
594 $required = FALSE;
595 }
596 else {
597 $required = TRUE;
598 }
599
600 $form->_priceSetId = $priceSetId;
601 $priceSet = self::getSetDetail($priceSetId, $required, $validOnly);
602 $form->_priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
603 $form->_values['fee'] = CRM_Utils_Array::value('fields', $form->_priceSet);
604
605 //get the price set fields participant count.
606 if ($entityTable == 'civicrm_event') {
607 //get option count info.
608 $form->_priceSet['optionsCountTotal'] = self::getPricesetCount($priceSetId);
609 if ($form->_priceSet['optionsCountTotal']) {
610 $optionsCountDeails = array();
611 if (!empty($form->_priceSet['fields'])) {
612 foreach ($form->_priceSet['fields'] as $field) {
613 foreach ($field['options'] as $option) {
614 $count = CRM_Utils_Array::value('count', $option, 0);
615 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
616 }
617 }
618 }
619 $form->_priceSet['optionsCountDetails'] = $optionsCountDeails;
620 }
621
622 //get option max value info.
623 $optionsMaxValueTotal = 0;
624 $optionsMaxValueDetails = array();
625
626 if (!empty($form->_priceSet['fields'])) {
627 foreach ($form->_priceSet['fields'] as $field) {
628 foreach ($field['options'] as $option) {
629 $maxVal = CRM_Utils_Array::value('max_value', $option, 0);
630 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
631 $optionsMaxValueTotal += $maxVal;
632 }
633 }
634 }
635
636 $form->_priceSet['optionsMaxValueTotal'] = $optionsMaxValueTotal;
637 if ($optionsMaxValueTotal) {
638 $form->_priceSet['optionsMaxValueDetails'] = $optionsMaxValueDetails;
639 }
640 }
641 $form->set('priceSetId', $form->_priceSetId);
642 $form->set('priceSet', $form->_priceSet);
643
644 return $priceSetId;
645 }
646 return FALSE;
647 }
648
649 /**
650 * Process amount.
651 *
652 * @param array $fields
653 * @param array $params
654 * @param array $lineItem
655 */
656 public static function processAmount(&$fields, &$params, &$lineItem) {
657 // using price set
658 $totalPrice = 0;
659 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
660
661 foreach ($fields as $id => $field) {
662 if (empty($params["price_{$id}"]) ||
663 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
664 ) {
665 // skip if nothing was submitted for this field
666 continue;
667 }
668
669 switch ($field['html_type']) {
670 case 'Text':
671 $params["price_{$id}"] = array(key($field['options']) => $params["price_{$id}"]);
672 CRM_Upgrade_Snapshot_V4p2_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
673 $totalPrice += $lineItem[key($field['options'])]['line_total'];
674 break;
675
676 case 'Radio':
677 //special case if user select -none-
678 if ($params["price_{$id}"] <= 0) {
679 continue;
680 }
681 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
682 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
683 $optionLabel = CRM_Utils_Array::value('label', $field['options'][$optionValueId]);
684 $params['amount_priceset_level_radio'] = array();
685 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
686 if (isset($radioLevel)) {
687 $radioLevel = array_merge($radioLevel,
688 array_keys($params['amount_priceset_level_radio'])
689 );
690 }
691 else {
692 $radioLevel = array_keys($params['amount_priceset_level_radio']);
693 }
694 CRM_Upgrade_Snapshot_V4p2_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
695 $totalPrice += $lineItem[$optionValueId]['line_total'];
696 break;
697
698 case 'Select':
699 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
700 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
701 $optionLabel = $field['options'][$optionValueId]['label'];
702 $params['amount_priceset_level_select'] = array();
703 $params['amount_priceset_level_select'][CRM_Utils_Array::key(1, $params["price_{$id}"])] = $optionLabel;
704 if (isset($selectLevel)) {
705 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
706 }
707 else {
708 $selectLevel = array_keys($params['amount_priceset_level_select']);
709 }
710 CRM_Upgrade_Snapshot_V4p2_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
711 $totalPrice += $lineItem[$optionValueId]['line_total'];
712 break;
713
714 case 'CheckBox':
715 $params['amount_priceset_level_checkbox'] = $optionIds = array();
716 foreach ($params["price_{$id}"] as $optionId => $option) {
717 $optionIds[] = $optionId;
718 $optionLabel = $field['options'][$optionId]['label'];
719 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
720 if (isset($checkboxLevel)) {
721 $checkboxLevel = array_unique(array_merge(
722 $checkboxLevel,
723 array_keys($params['amount_priceset_level_checkbox'])
724 )
725 );
726 }
727 else {
728 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
729 }
730 }
731 CRM_Upgrade_Snapshot_V4p2_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
732 foreach ($optionIds as $optionId) {
733 $totalPrice += $lineItem[$optionId]['line_total'];
734 }
735 break;
736 }
737 }
738
739 $amount_level = array();
740 $totalParticipant = 0;
741 if (is_array($lineItem)) {
742 foreach ($lineItem as $values) {
743 $totalParticipant += $values['participant_count'];
744 if ($values['html_type'] == 'Text') {
745 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
746 continue;
747 }
748 $amount_level[] = $values['label'];
749 }
750 }
751
752 $displayParticipantCount = '';
753 if ($totalParticipant > 0) {
754 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
755 }
756
757 $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
758 $params['amount'] = $totalPrice;
759 }
760
761 /**
762 * Build the price set form.
763 *
764 * @param CRM_Core_Form $form
765 */
766 public static function buildPriceSet(&$form) {
767 $priceSetId = $form->get('priceSetId');
768 $userid = $form->getVar('_userID');
769 if (!$priceSetId) {
770 return;
771 }
772
773 $validFieldsOnly = TRUE;
774 $className = CRM_Utils_System::getClassName($form);
775 if (in_array($className, array(
776 'CRM_Contribute_Form_Contribution',
777 'CRM_Member_Form_Membership',
778 ))) {
779 $validFieldsOnly = FALSE;
780 }
781
782 $priceSet = self::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
783 $form->_priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
784 $form->_quickConfig = $quickConfig = 0;
785 if (CRM_Core_DAO::getFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set', $priceSetId, 'is_quick_config')) {
786 $quickConfig = 1;
787 }
788
789 $form->assign('quickConfig', $quickConfig);
790 if ($className == "CRM_Contribute_Form_Contribution_Main") {
791 $form->_quickConfig = $quickConfig;
792 }
793 $form->assign('priceSet', $form->_priceSet);
794
795 $component = 'contribution';
796 if ($className == 'CRM_Member_Form_Membership') {
797 $component = 'membership';
798 }
799
800 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
801 $feeBlock = &$form->_values['fee'];
802 if (!empty($form->_useForMember)) {
803 $component = 'membership';
804 }
805 }
806 else {
807 $feeBlock = &$form->_priceSet['fields'];
808 }
809
810 // call the hook.
811 CRM_Utils_Hook::buildAmount($component, $form, $feeBlock);
812
813 foreach ($feeBlock as $field) {
814 if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
815 !$validFieldsOnly
816 ) {
817 $options = CRM_Utils_Array::value('options', $field);
818 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
819 $checklifetime = self::checkCurrentMembership($options, $userid);
820 if ($checklifetime) {
821 $form->assign('ispricelifetime', TRUE);
822 }
823 }
824 if (!is_array($options)) {
825 continue;
826 }
827 CRM_Upgrade_Snapshot_V4p2_Price_BAO_Field::addQuickFormElement($form,
828 'price_' . $field['id'],
829 $field['id'],
830 FALSE,
831 CRM_Utils_Array::value('is_required', $field, FALSE),
832 NULL,
833 $options
834 );
835 }
836 }
837 }
838
839 /**
840 * Check the current Membership.
841 *
842 * @param array $options
843 * @param int $userid
844 *
845 * @return bool
846 */
847 public static function checkCurrentMembership(&$options, $userid) {
848 if (!$userid || empty($options)) {
849 return FALSE;
850 }
851 static $_contact_memberships = array();
852 $checklifetime = FALSE;
853 foreach ($options as $key => $value) {
854 if (!empty($value['membership_type_id'])) {
855 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
856 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership::getContactMembership($userid, $value['membership_type_id'], FALSE);
857 }
858 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
859 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
860 unset($options[$key]);
861 $checklifetime = TRUE;
862 }
863 }
864 }
865 if ($checklifetime) {
866 return TRUE;
867 }
868 else {
869 return FALSE;
870 }
871 }
872
873 /**
874 * Set default the price set fields.
875 *
876 * @param CRM_Core_Form $form
877 * @param array $defaults
878 *
879 * @return array
880 */
881 public static function setDefaultPriceSet(&$form, &$defaults) {
882 if (!isset($form->_priceSet) || empty($form->_priceSet['fields'])) {
883 return $defaults;
884 }
885
886 foreach ($form->_priceSet['fields'] as $key => $val) {
887 foreach ($val['options'] as $keys => $values) {
888 if ($values['is_default']) {
889 if ($val['html_type'] == 'CheckBox') {
890 $defaults["price_{$key}"][$keys] = 1;
891 }
892 else {
893 $defaults["price_{$key}"] = $keys;
894 }
895 }
896 }
897 }
898 return $defaults;
899 }
900
901 /**
902 * Get field ids of a price set.
903 *
904 * @param int $id Price Set id
905 *
906 * @return array
907 * Array of the field ids
908 */
909 public static function getFieldIds($id) {
910 $priceField = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field();
911 $priceField->price_set_id = $id;
912 $priceField->find();
913 while ($priceField->fetch()) {
914 $var[] = $priceField->id;
915 }
916 return $var;
917 }
918
919 /**
920 * Copy a price set, including all the fields.
921 *
922 * @param int $id
923 * The price set id to copy.
924 *
925 * @return CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field
926 */
927 public static function copy($id) {
928 $maxId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
929
930 $title = ts('[Copy id %1]', array(1 => $maxId + 1));
931 $fieldsFix = array(
932 'suffix' => array(
933 'title' => ' ' . $title,
934 'name' => '__Copy_id_' . ($maxId + 1) . '_',
935 ),
936 );
937
938 $copy = &CRM_Core_DAO::copyGeneric('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set',
939 array('id' => $id),
940 NULL,
941 $fieldsFix
942 );
943
944 //copying all the blocks pertaining to the price set
945 $copyPriceField = &CRM_Core_DAO::copyGeneric('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field',
946 array('price_set_id' => $id),
947 array('price_set_id' => $copy->id)
948 );
949 if (!empty($copyPriceField)) {
950 $price = array_combine(self::getFieldIds($id), self::getFieldIds($copy->id));
951
952 //copy option group and values
953 foreach ($price as $originalId => $copyId) {
954 CRM_Core_DAO::copyGeneric('CRM_Upgrade_Snapshot_V4p2_Price_DAO_FieldValue',
955 array('price_field_id' => $originalId),
956 array('price_field_id' => $copyId)
957 );
958 }
959 }
960 $copy->save();
961
962 CRM_Utils_Hook::copy('Set', $copy);
963 return $copy;
964 }
965
966 /**
967 * Check price set permission.
968 *
969 * @param int $sid
970 * The price set id.
971 *
972 * @return bool
973 */
974 public function checkPermission($sid) {
975 if ($sid &&
976 self::eventPriceSetDomainID()
977 ) {
978 $domain_id = CRM_Core_DAO::getFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set', $sid, 'domain_id', 'id');
979 if (CRM_Core_Config::domainID() != $domain_id) {
980 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
981 }
982 }
983 return TRUE;
984 }
985
986 /**
987 * Get the sum of participant count for all fields of given price set.
988 *
989 * @param int $sid
990 * The price set id.
991 *
992 * @param bool $onlyActive
993 *
994 * @return int|null|string
995 */
996 public static function getPricesetCount($sid, $onlyActive = TRUE) {
997 $count = 0;
998 if (!$sid) {
999 return $count;
1000 }
1001
1002 $where = NULL;
1003 if ($onlyActive) {
1004 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1005 }
1006
1007 static $pricesetFieldCount;
1008 if (!isset($pricesetFieldCount[$sid])) {
1009 $sql = "
1010 SELECT sum(value.count) as totalCount
1011 FROM civicrm_price_field_value value
1012 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1013 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1014 WHERE pset.id = %1
1015 $where";
1016
1017 $count = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1018 $pricesetFieldCount[$sid] = ($count) ? $count : 0;
1019 }
1020
1021 return $pricesetFieldCount[$sid];
1022 }
1023
1024 /**
1025 * Get membership count.
1026 *
1027 * @param array $ids
1028 *
1029 * @return array
1030 */
1031 public static function getMembershipCount($ids) {
1032 $queryString = "
1033 SELECT count( pfv.id ) AS count, pfv.id AS id
1034 FROM civicrm_price_field_value pfv
1035 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1036 WHERE pfv.id IN ( $ids )
1037 GROUP BY mt.member_of_contact_id";
1038
1039 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
1040 $count = array();
1041
1042 while ($crmDAO->fetch()) {
1043 $count[$crmDAO->id] = $crmDAO->count;
1044 }
1045
1046 return $count;
1047 }
1048
1049 /**
1050 * Function to check if auto renew option should be shown.
1051 *
1052 * @param int $priceSetId
1053 * Price set id.
1054 *
1055 * @return int
1056 * $autoRenewOption ( 0:hide, 1:optional 2:required )
1057 */
1058 public static function checkAutoRenewForPriceSet($priceSetId) {
1059 // auto-renew option should be visible if membership types associated with all the fields has
1060 // been set for auto-renew option
1061 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1062
1063 // get the membership type auto renew option and check if required or optional
1064 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1065 FROM civicrm_price_field_value pfv
1066 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1067 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1068 WHERE pf.price_set_id = %1
1069 AND pf.is_active = 1
1070 AND pfv.is_active = 1';
1071
1072 $params = array(1 => array($priceSetId, 'Integer'));
1073
1074 $dao = CRM_Core_DAO::executeQuery($query, $params);
1075 $autoRenewOption = 2;
1076 $interval = $unit = array();
1077 while ($dao->fetch()) {
1078 if (!$dao->auto_renew) {
1079 $autoRenewOption = 0;
1080 break;
1081 }
1082 if ($dao->auto_renew == 1) {
1083 $autoRenewOption = 1;
1084 }
1085
1086 $interval[$dao->duration_interval] = $dao->duration_interval;
1087 $unit[$dao->duration_unit] = $dao->duration_unit;
1088 }
1089
1090 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1091 return $autoRenewOption;
1092 }
1093 else {
1094 return 0;
1095 }
1096 }
1097
1098 /**
1099 * Retrieve auto renew frequency and interval.
1100 *
1101 * @param int $priceSetId
1102 * Price set id.
1103 *
1104 * @return array
1105 * associate array of frequency interval and unit
1106 */
1107 public static function getRecurDetails($priceSetId) {
1108 $query = 'SELECT mt.duration_interval, mt.duration_unit
1109 FROM civicrm_price_field_value pfv
1110 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1111 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1112 WHERE pf.price_set_id = %1 LIMIT 1';
1113
1114 $params = array(1 => array($priceSetId, 'Integer'));
1115 $dao = CRM_Core_DAO::executeQuery($query, $params);
1116 $dao->fetch();
1117 return array($dao->duration_interval, $dao->duration_unit);
1118 }
1119
1120 /**
1121 * Get event price set for domain.
1122 *
1123 * @return object
1124 */
1125 public static function eventPriceSetDomainID() {
1126 return CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME,
1127 'event_price_set_domain_id',
1128 NULL, FALSE
1129 );
1130 }
1131
1132 /**
1133 * Update the is_quick_config flag in the db.
1134 *
1135 * @param int $id
1136 * Id of the database record.
1137 * @param bool $isQuickConfig we want to set the is_quick_config field.
1138 * Value we want to set the is_quick_config field.
1139 *
1140 * @return Object
1141 * DAO object on success, null otherwise
1142 */
1143 public static function setIsQuickConfig($id, $isQuickConfig) {
1144 return CRM_Core_DAO::setFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set', $id, 'is_quick_config', $isQuickConfig);
1145 }
1146
1147 }