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