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