INFRA-132 - Civi - PHPStorm cleanup
[civicrm-core.git] / CRM / Upgrade / Snapshot / V4p2 / Price / BAO / Set.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 * Business object for managing price sets
38 *
39 */
40class CRM_Upgrade_Snapshot_V4p2_Price_BAO_Set extends CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set {
41
42 /**
100fef9d 43 * Class constructor
6a488035 44 */
00be9182 45 public function __construct() {
6a488035
TO
46 parent::__construct();
47 }
48
49 /**
100fef9d 50 * Takes an associative array and creates a price set object
6a488035 51 *
c68f8bfa
TO
52 * @param array $params
53 * (reference) an assoc array of name/value pairs.
6a488035 54 *
c490a46a 55 * @return CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set object
6a488035
TO
56 * @static
57 */
00be9182 58 public static function create(&$params) {
6a488035
TO
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 /**
c490a46a 68 * Fetch object based on array of properties
6a488035 69 *
c68f8bfa
TO
70 * @param array $params
71 * (reference ) an assoc array of name/value pairs.
72 * @param array $defaults
73 * (reference ) an assoc array to hold the flattened values.
6a488035 74 *
c490a46a 75 * @return CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set object
6a488035
TO
76 * @static
77 */
00be9182 78 public static function retrieve(&$params, &$defaults) {
6a488035
TO
79 return CRM_Core_DAO::commonRetrieve('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set', $params, $defaults);
80 }
81
82 /**
100fef9d 83 * Update the is_active flag in the db
6a488035 84 *
c68f8bfa
TO
85 * @param int $id
86 * Id of the database record.
87 * @param bool $isActive
88 * Value we want to set the is_active field.
6a488035 89 *
a6c01b45
CW
90 * @return Object
91 * DAO object on sucess, null otherwise
6a488035 92 * @static
6a488035 93 */
00be9182 94 public static function setIsActive($id, $isActive) {
6a488035
TO
95 return CRM_Core_DAO::setFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set', $id, 'is_active', $isActive);
96 }
97
10824d34 98 /**
6a488035
TO
99 * Calculate the default price set id
100 * assigned to the contribution/membership etc
101 *
102 * @param string $entity
103 *
104 * @return id $priceSetID
105 *
6a488035 106 * @static
6a488035
TO
107 */
108 public static function getDefaultPriceSet($entity = 'contribution') {
109 if ($entity == 'contribution') {
110 $entityName = 'default_contribution_amount';
111 }
4c9b6178 112 elseif ($entity == 'membership') {
6a488035
TO
113 $entityName = 'default_membership_type_amount';
114 }
115
116 $sql = "
117SELECT ps.id AS setID, pfv.price_field_id AS priceFieldID, pfv.id AS priceFieldValueID, pfv.name, pfv.label
118FROM civicrm_price_set ps
119LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
120LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
121WHERE ps.name = '{$entityName}'
122";
123
124 $dao = CRM_Core_DAO::executeQuery($sql);
125 $defaultPriceSet = array();
126 while ($dao->fetch()) {
e418776c
TO
127 $defaultPriceSet[$dao->priceFieldValueID]['setID'] = $dao->setID;
128 $defaultPriceSet[$dao->priceFieldValueID]['priceFieldID'] = $dao->priceFieldID;
129 $defaultPriceSet[$dao->priceFieldValueID]['name'] = $dao->name;
130 $defaultPriceSet[$dao->priceFieldValueID]['label'] = $dao->label;
6a488035
TO
131 }
132
6a488035
TO
133 return $defaultPriceSet;
134 }
135
136 /**
137 * Get the price set title.
138 *
c68f8bfa
TO
139 * @param int $id
140 * Id of price set.
6a488035 141 *
a6c01b45
CW
142 * @return string
143 * title
6a488035 144 *
6a488035 145 * @static
6a488035
TO
146 */
147 public static function getTitle($id) {
148 return CRM_Core_DAO::getFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set', $id, 'title');
149 }
150
151 /**
152 * Return a list of all forms which use this price set.
153 *
c68f8bfa
TO
154 * @param int $id
155 * Id of price set.
77b97be7 156 * @param bool|\str $simpleReturn - get raw data. Possible values: 'entity', 'table'
6a488035
TO
157 *
158 * @return array
159 */
160 public static function &getUsedBy($id, $simpleReturn = FALSE) {
161 $usedBy = $forms = $tables = array();
162 $queryString = "
163SELECT entity_table, entity_id
164FROM civicrm_price_set_entity
165WHERE price_set_id = %1";
166 $params = array(1 => array($id, 'Integer'));
167 $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
168
169 while ($crmFormDAO->fetch()) {
170 $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
171 $tables[] = $crmFormDAO->entity_table;
172 }
173 // Return only tables
174 if ($simpleReturn == 'table') {
175 return $tables;
176 }
177 if (empty($forms)) {
e418776c 178 $queryString = "
6a488035
TO
179SELECT cli.entity_table, cli.entity_id
180FROM civicrm_line_item cli
181LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
182WHERE cpf.price_set_id = %1";
183 $params = array(1 => array($id, 'Integer'));
184 $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
185 while ($crmFormDAO->fetch()) {
186 $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
187 $tables[] = $crmFormDAO->entity_table;
188 }
189 if (empty($forms)) {
190 return $usedBy;
191 }
192 }
193 // Return only entity data
194 if ($simpleReturn == 'entity') {
195 return $forms;
196 }
197 foreach ($forms as $table => $entities) {
198 switch ($table) {
199 case 'civicrm_event':
200 $ids = implode(',', $entities);
201 $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
202FROM civicrm_event ce
203LEFT JOIN civicrm_option_value ON
204 ( ce.event_type_id = civicrm_option_value.value )
205LEFT JOIN civicrm_option_group ON
206 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
207WHERE
10824d34 208 civicrm_option_group.name = 'event_type' AND
6a488035
TO
209 ( ce.is_template IS NULL OR ce.is_template = 0) AND
210 ce.id IN ($ids) AND
211 ce.is_active = 1;";
212 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
213 while ($crmDAO->fetch()) {
214 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
215 $usedBy[$table][$crmDAO->id]['eventType'] = $crmDAO->eventType;
216 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
217 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
218 $usedBy[$table][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
219 }
220 break;
221
222 case 'civicrm_contribution_page':
223 $ids = implode(',', $entities);
224 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
225FROM civicrm_contribution_page cp, civicrm_contribution_type ct
226WHERE ct.id = cp.contribution_type_id AND
227 cp.id IN ($ids) AND
228 cp.is_active = 1;";
229 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
230 while ($crmDAO->fetch()) {
231 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
232 $usedBy[$table][$crmDAO->id]['type'] = $crmDAO->type;
233 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
234 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
235 }
236 break;
237
238 case 'civicrm_contribution':
239 case 'civicrm_membership':
240 case 'civicrm_participant':
241 $usedBy[$table] = 1;
242 break;
243
244 default:
245 CRM_Core_Error::fatal("$table is not supported in PriceSet::usedBy()");
246 break;
247 }
248 }
249
250 return $usedBy;
251 }
252
253 /**
254 * Delete the price set
255 *
c68f8bfa
TO
256 * @param int $id
257 * Price Set id.
6a488035 258 *
a6c01b45
CW
259 * @return boolean
260 * false if fields exist for this set, true if the
6a488035
TO
261 * set could be deleted
262 *
6a488035
TO
263 * @static
264 */
265 public static function deleteSet($id) {
266 // remove from all inactive forms
267 $usedBy = self::getUsedBy($id);
268 if (isset($usedBy['civicrm_event'])) {
269 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
270 $eventDAO = new CRM_Event_DAO_Event();
271 $eventDAO->id = $eventId;
272 $eventDAO->find();
273 while ($eventDAO->fetch()) {
274 self::removeFrom('civicrm_event', $eventDAO->id);
275 }
276 }
277 }
278
279 // delete price fields
280 $priceField = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field();
281 $priceField->price_set_id = $id;
282 $priceField->find();
283 while ($priceField->fetch()) {
284 // delete options first
285 CRM_Upgrade_Snapshot_V4p2_Price_BAO_Field::deleteField($priceField->id);
286 }
287
288 $set = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set();
289 $set->id = $id;
290 return $set->delete();
291 }
292
293 /**
294 * Link the price set with the specified table and id
295 *
296 * @param string $entityTable
c68f8bfa
TO
297 * @param int $entityId
298 * @param int $priceSetId
6a488035
TO
299 *
300 * @return bool
301 */
302 public static function addTo($entityTable, $entityId, $priceSetId) {
303 // verify that the price set exists
304 $dao = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set();
305 $dao->id = $priceSetId;
306 if (!$dao->find()) {
307 return FALSE;
308 }
309 unset($dao);
310
311 $dao = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_SetEntity();
312 // find if this already exists
313 $dao->entity_id = $entityId;
314 $dao->entity_table = $entityTable;
315 $dao->find(TRUE);
316
317 // add or update price_set_id
318 $dao->price_set_id = $priceSetId;
319 return $dao->save();
320 }
321
322 /**
323 * Delete price set for the given entity and id
324 *
325 * @param string $entityTable
c68f8bfa 326 * @param int $entityId
77b97be7
EM
327 *
328 * @return mixed
6a488035
TO
329 */
330 public static function removeFrom($entityTable, $entityId) {
331 $dao = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_SetEntity();
332 $dao->entity_table = $entityTable;
333 $dao->entity_id = $entityId;
334 return $dao->delete();
335 }
336
337 /**
338 * Find a price_set_id associatied with the given table, id and usedFor
339 * Used For value for events:1, contribution:2, membership:3
340 *
341 * @param string $entityTable
77b97be7 342 * @param int $entityId
c68f8bfa
TO
343 * @param int $usedFor
344 * ( price set that extends/used for particular component ).
77b97be7
EM
345 *
346 * @param null $isQuickConfig
347 * @param null $setName
6a488035
TO
348 *
349 * @return integer|false price_set_id, or false if none found
350 */
351 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
352 if (!$entityTable || !$entityId) {
353 return FALSE;
354 }
355
356 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
357 FROM civicrm_price_set ps
358 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
359 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
360 if ($isQuickConfig) {
361 $sql .= " AND ps.is_quick_config = 0 ";
362 }
e418776c
TO
363 $params = array(
364 1 => array($entityTable, 'String'),
6a488035
TO
365 2 => array($entityId, 'Integer'),
366 );
367 if ($usedFor) {
368 $sql .= " AND ps.extends LIKE '%%3%' ";
369 $params[3] = array($usedFor, 'Integer');
370 }
371
372 $dao = CRM_Core_DAO::executeQuery($sql, $params);
373 $dao->fetch();
374 $setName = (isset($dao->price_set_name)) ? $dao->price_set_name : FALSE;
375 return (isset($dao->price_set_id)) ? $dao->price_set_id : FALSE;
376 }
377
378 /**
379 * Find a price_set_id associatied with the given option value or field ID
380 *
c68f8bfa
TO
381 * @param array $params
382 * (reference) an assoc array of name/value pairs.
6a488035
TO
383 * array may contain either option id or
384 * price field id
385 *
386 * @return price set id on success, null otherwise
387 * @static
6a488035
TO
388 */
389 public static function getSetId(&$params) {
390 $fid = NULL;
391
392 if ($oid = CRM_Utils_Array::value('oid', $params)) {
393 $fieldValue = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_FieldValue();
394 $fieldValue->id = $oid;
395 if ($fieldValue->find(TRUE)) {
396 $fid = $fieldValue->price_field_id;
397 }
398 }
399 else {
400 $fid = CRM_Utils_Array::value('fid', $params);
401 }
402
403 if (isset($fid)) {
404 return CRM_Core_DAO::getFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field', $fid, 'price_set_id');
405 }
406
407 return NULL;
408 }
409
410 /**
411 * Return an associative array of all price sets
412 *
c68f8bfa
TO
413 * @param bool $withInactive
414 * Whether or not to include inactive entries.
77b97be7 415 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
6a488035 416 *
a6c01b45
CW
417 * @return array
418 * associative array of id => name
6a488035
TO
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 *
c68f8bfa
TO
460 * @param int $setID
461 * Price set id whose details are needed.
77b97be7
EM
462 * @param bool $required
463 * @param bool $validOnly
464 *
a6c01b45
CW
465 * @return array
466 * array consisting of field details
6a488035
TO
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 = '
502WHERE price_set_id = %1
503AND is_active = 1
504';
505 $dateSelect = '';
506 if ($validOnly) {
507 $currentTime = date('YmdHis');
508 $dateSelect = "
509AND ( active_on IS NULL OR active_on <= {$currentTime} )
510AND ( 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 = "
542SELECT extends, contribution_type_id, help_pre, help_post, is_quick_config
543FROM civicrm_price_set
544WHERE 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
624e56fa 556 /**
c490a46a 557 * @param CRM_Core_Form $form
100fef9d 558 * @param int $id
624e56fa
EM
559 * @param string $entityTable
560 * @param bool $validOnly
100fef9d 561 * @param int $priceSetId
624e56fa
EM
562 *
563 * @return bool|false|int|null
564 */
00be9182 565 public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
6a488035
TO
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
624e56fa
EM
657 /**
658 * @param $fields
c490a46a 659 * @param array $params
624e56fa
EM
660 * @param $lineItem
661 */
00be9182 662 public static function processAmount(&$fields, &$params, &$lineItem) {
6a488035
TO
663 // using price set
664 $totalPrice = 0;
665 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
666
667 foreach ($fields as $id => $field) {
a7488080 668 if (empty($params["price_{$id}"]) ||
6a488035
TO
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 }
e418776c
TO
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,
6a488035 694 array_keys($params['amount_priceset_level_radio'])
e418776c
TO
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;
6a488035
TO
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)) {
e418776c
TO
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
720 case 'CheckBox':
721 $params['amount_priceset_level_checkbox'] = $optionIds = array();
722 foreach ($params["price_{$id}"] as $optionId => $option) {
723 $optionIds[] = $optionId;
724 $optionLabel = $field['options'][$optionId]['label'];
725 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
726 if (isset($checkboxLevel)) {
727 $checkboxLevel = array_unique(array_merge(
728 $checkboxLevel,
729 array_keys($params['amount_priceset_level_checkbox'])
730 )
731 );
732 }
733 else {
734 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
735 }
736 }
737 CRM_Upgrade_Snapshot_V4p2_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
738 foreach ($optionIds as $optionId) {
739 $totalPrice += $lineItem[$optionId]['line_total'];
740 }
741 break;
6a488035
TO
742 }
743 }
744
745 $amount_level = array();
746 $totalParticipant = 0;
747 if (is_array($lineItem)) {
748 foreach ($lineItem as $values) {
749 $totalParticipant += $values['participant_count'];
750 if ($values['html_type'] == 'Text') {
751 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
752 continue;
753 }
754 $amount_level[] = $values['label'];
755 }
756 }
757
758 $displayParticipantCount = '';
759 if ($totalParticipant > 0) {
760 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
761 }
762
763 $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
764 $params['amount'] = $totalPrice;
765 }
766
77b97be7 767 /**
100fef9d 768 * Build the price set form.
77b97be7 769 *
c490a46a 770 * @param CRM_Core_Form $form
77b97be7
EM
771 *
772 * @return void
77b97be7 773 */
e418776c
TO
774 static function buildPriceSet(&$form) {
775 $priceSetId = $form->get('priceSetId');
776 $userid = $form->getVar('_userID');
777 if (!$priceSetId) {
778 return;
779 }
6a488035 780
e418776c
TO
781 $validFieldsOnly = TRUE;
782 $className = CRM_Utils_System::getClassName($form);
783 if (in_array($className, array(
6a488035 784 'CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'))) {
e418776c
TO
785 $validFieldsOnly = FALSE;
786 }
6a488035 787
e418776c
TO
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 }
6a488035 794
e418776c
TO
795 $form->assign('quickConfig', $quickConfig);
796 if ($className == "CRM_Contribute_Form_Contribution_Main") {
797 $form->_quickConfig = $quickConfig;
798 }
799 $form->assign('priceSet', $form->_priceSet);
6a488035 800
e418776c
TO
801 $component = 'contribution';
802 if ($className == 'CRM_Member_Form_Membership') {
803 $component = 'membership';
804 }
6a488035 805
e418776c
TO
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 }
6a488035 815
e418776c
TO
816 // call the hook.
817 CRM_Utils_Hook::buildAmount($component, $form, $feeBlock);
6a488035 818
e418776c
TO
819 foreach ($feeBlock as $field) {
820 if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
6a488035
TO
821!$validFieldsOnly
822) {
e418776c
TO
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 }
6a488035 844
e418776c
TO
845 /**
846 * 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 }
6a488035 874
2a6da8d7 875 /**
100fef9d 876 * Set daefult the price set fields.
2a6da8d7 877 *
c490a46a 878 * @param CRM_Core_Form $form
2a6da8d7
EM
879 * @param $defaults
880 *
a6c01b45 881 * @return array
2a6da8d7 882 */
e418776c
TO
883 static function setDefaultPriceSet(&$form, &$defaults) {
884 if (!isset($form->_priceSet) || empty($form->_priceSet['fields'])) {
885 return $defaults;
886 }
6a488035 887
e418776c
TO
888 foreach ($form->_priceSet['fields'] as $key => $val) {
889 foreach ($val['options'] as $keys => $values) {
890 if ($values['is_default']) {
891 if ($val['html_type'] == 'CheckBox') {
892 $defaults["price_{$key}"][$keys] = 1;
893 }
894 else {
895 $defaults["price_{$key}"] = $keys;
896 }
897 }
898 }
899 }
900 return $defaults;
901 }
6a488035 902
e418776c
TO
903 /**
904 * Get field ids of a price set
905 *
906 * @param int id Price Set id
907 *
a6c01b45
CW
908 * @return array
909 * of the field ids
e418776c
TO
910 *
911 * @static
912 */
913 public static function getFieldIds($id) {
914 $priceField = new CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field();
915 $priceField->price_set_id = $id;
916 $priceField->find();
917 while ($priceField->fetch()) {
918 $var[] = $priceField->id;
919 }
920 return $var;
921 }
6a488035 922
e418776c 923 /**
dc195289 924 * make a copy of a price set, including
e418776c
TO
925 * all the fields
926 *
927 * @param int $id
928 * The price set id to copy.
929 *
930 * @return the copy object
931 * @static
932 */
933 static function copy($id) {
934 $maxId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
935
936 $title = ts('[Copy id %1]', array(1 => $maxId + 1));
937 $fieldsFix = array(
938 'suffix' => array(
939 'title' => ' ' . $title,
940 'name' => '__Copy_id_' . ($maxId + 1) . '_',
941 ),
942 );
6a488035 943
e418776c
TO
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 }
6a488035 971
77b97be7 972 /**
dc195289 973 * check price set permission
77b97be7 974 *
c68f8bfa
TO
975 * @param int $sid
976 * The price set id.
77b97be7
EM
977 *
978 * @return bool
979 */
e418776c
TO
980 function checkPermission($sid) {
981 if ($sid &&
6a488035
TO
982self::eventPriceSetDomainID()
983) {
e418776c
TO
984 $domain_id = CRM_Core_DAO::getFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set', $sid, 'domain_id', 'id');
985 if (CRM_Core_Config::domainID() != $domain_id) {
986 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
987 }
988 }
989 return TRUE;
990 }
6a488035 991
77b97be7
EM
992 /**
993 * Get the sum of participant count
994 * for all fields of given price set.
995 *
c68f8bfa
TO
996 * @param int $sid
997 * The price set id.
77b97be7
EM
998 *
999 * @param bool $onlyActive
1000 *
1001 * @return int|null|string
77b97be7
EM
1002 * @static
1003 */
e418776c
TO
1004 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1005 $count = 0;
1006 if (!$sid) {
1007 return $count;
1008 }
6a488035 1009
e418776c
TO
1010 $where = NULL;
1011 if ($onlyActive) {
1012 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1013 }
6a488035 1014
e418776c
TO
1015 static $pricesetFieldCount;
1016 if (!isset($pricesetFieldCount[$sid])) {
1017 $sql = "
6a488035
TO
1018 SELECT sum(value.count) as totalCount
1019 FROM civicrm_price_field_value value
1020INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1021INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1022 WHERE pset.id = %1
1023 $where";
1024
e418776c
TO
1025 $count = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1026 $pricesetFieldCount[$sid] = ($count) ? $count : 0;
1027 }
6a488035 1028
e418776c
TO
1029 return $pricesetFieldCount[$sid];
1030 }
6a488035 1031
624e56fa
EM
1032 /**
1033 * @param $ids
1034 *
1035 * @return array
95ea96be
EM
1036 */
1037 public static function getMembershipCount($ids) {
e418776c 1038 $queryString = "
6a488035
TO
1039SELECT count( pfv.id ) AS count, pfv.id AS id
1040FROM civicrm_price_field_value pfv
1041INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1042WHERE pfv.id IN ( $ids )
1043GROUP BY mt.member_of_contact_id";
1044
e418776c
TO
1045 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
1046 $count = array();
6a488035 1047
e418776c
TO
1048 while ($crmDAO->fetch()) {
1049 $count[$crmDAO->id] = $crmDAO->count;
1050 }
6a488035 1051
e418776c
TO
1052 return $count;
1053 }
6a488035 1054
e418776c
TO
1055 /**
1056 * Function to check if auto renew option should be shown
1057 *
1058 * @param int $priceSetId
1059 * Price set id.
1060 *
a6c01b45
CW
1061 * @return int
1062 * $autoRenewOption ( 0:hide, 1:optional 2:required )
e418776c
TO
1063 */
1064 public static function checkAutoRenewForPriceSet($priceSetId) {
1065 // auto-renew option should be visible if membership types associated with all the fields has
1066 // been set for auto-renew option
1067 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
6a488035 1068
e418776c
TO
1069 // get the membership type auto renew option and check if required or optional
1070 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
6a488035
TO
1071 FROM civicrm_price_field_value pfv
1072 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1073 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1074 WHERE pf.price_set_id = %1
1075 AND pf.is_active = 1
1076 AND pfv.is_active = 1';
1077
e418776c 1078 $params = array(1 => array($priceSetId, 'Integer'));
6a488035 1079
e418776c
TO
1080 $dao = CRM_Core_DAO::executeQuery($query, $params);
1081 $autoRenewOption = 2;
1082 $interval = $unit = array();
1083 while ($dao->fetch()) {
1084 if (!$dao->auto_renew) {
1085 $autoRenewOption = 0;
1086 break;
1087 }
1088 if ($dao->auto_renew == 1) {
1089 $autoRenewOption = 1;
1090 }
6a488035 1091
e418776c
TO
1092 $interval[$dao->duration_interval] = $dao->duration_interval;
1093 $unit[$dao->duration_unit] = $dao->duration_unit;
1094 }
6a488035 1095
e418776c
TO
1096 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1097 return $autoRenewOption;
1098 }
1099 else {
1100 return 0;
1101 }
1102 }
6a488035
TO
1103
1104 /**
100fef9d 1105 * Retrieve auto renew frequency and interval
6a488035 1106 *
c68f8bfa
TO
1107 * @param int $priceSetId
1108 * Price set id.
6a488035 1109 *
a6c01b45
CW
1110 * @return array
1111 * associate array of frequency interval and unit
6a488035 1112 * @static
10824d34 1113 */
e418776c
TO
1114 public static function getRecurDetails($priceSetId) {
1115 $query = 'SELECT mt.duration_interval, mt.duration_unit
6a488035
TO
1116 FROM civicrm_price_field_value pfv
1117 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1118 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1119 WHERE pf.price_set_id = %1 LIMIT 1';
1120
e418776c
TO
1121 $params = array(1 => array($priceSetId, 'Integer'));
1122 $dao = CRM_Core_DAO::executeQuery($query, $params);
1123 $dao->fetch();
1124 return array($dao->duration_interval, $dao->duration_unit);
1125 }
10824d34 1126
624e56fa
EM
1127 /**
1128 * @return object
1129 */
00be9182 1130 public static function eventPriceSetDomainID() {
6a488035
TO
1131 return CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME,
1132 'event_price_set_domain_id',
1133 NULL, FALSE
1134 );
1135 }
10824d34 1136
6a488035 1137 /**
100fef9d 1138 * Update the is_quick_config flag in the db
6a488035 1139 *
c68f8bfa
TO
1140 * @param int $id
1141 * Id of the database record.
e418776c 1142 * @param bool $isQuickConfigValue we want to set the is_quick_config field.
c68f8bfa 1143 * Value we want to set the is_quick_config field.
6a488035 1144 *
a6c01b45
CW
1145 * @return Object
1146 * DAO object on sucess, null otherwise
6a488035 1147 * @static
6a488035 1148 */
00be9182 1149 public static function setIsQuickConfig($id, $isQuickConfig) {
6a488035
TO
1150 return CRM_Core_DAO::setFieldValue('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set', $id, 'is_quick_config', $isQuickConfig);
1151 }
1152}