Merge pull request #3003 from generalredneck/CRM-14171
[civicrm-core.git] / CRM / Price / BAO / PriceField.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 objects for managing price fields.
38 *
39 */
40 class CRM_Price_BAO_PriceField extends CRM_Price_DAO_PriceField {
41
42 protected $_options;
43
44 /**
45 * takes an associative array and creates a price field object
46 *
47 * the function extract all the params it needs to initialize the create a
48 * price field object. the params array could contain additional unused name/value
49 * pairs
50 *
51 * @param array $params (reference ) an assoc array of name/value pairs
52 * @param array $ids the array that holds all the db ids
53 *
54 * @return object CRM_Price_BAO_PriceField object
55 * @access public
56 * @static
57 */
58 static function &add(&$params) {
59 $priceFieldBAO = new CRM_Price_BAO_PriceField();
60
61 $priceFieldBAO->copyValues($params);
62
63 if ($id = CRM_Utils_Array::value('id', $params)) {
64 $priceFieldBAO->id = $id;
65 }
66
67 $priceFieldBAO->save();
68 return $priceFieldBAO;
69 }
70
71 /**
72 * takes an associative array and creates a price field object
73 *
74 * This function is invoked from within the web form layer and also from the api layer
75 *
76 * @param array $params (reference) an assoc array of name/value pairs
77 *
78 * @return object CRM_Price_DAO_PriceField object
79 * @access public
80 * @static
81 */
82 static function create(&$params) {
83 $transaction = new CRM_Core_Transaction();
84
85 $priceField = self::add($params);
86
87 if (is_a($priceField, 'CRM_Core_Error')) {
88 $transaction->rollback();
89 return $priceField;
90 }
91
92 $options = $optionsIds = array();
93 $maxIndex = CRM_Price_Form_Field::NUM_OPTION;
94
95 if ($priceField->html_type == 'Text') {
96 $maxIndex = 1;
97
98 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
99 $fieldValue->price_field_id = $priceField->id;
100
101 // update previous field values( if any )
102 if ($fieldValue->find(TRUE)) {
103 $optionsIds['id'] = $fieldValue->id;
104 }
105 }
106 $defaultArray = array();
107 if ($params['html_type'] == 'CheckBox' && isset($params['default_checkbox_option'])) {
108 $tempArray = array_keys($params['default_checkbox_option']);
109 foreach ($tempArray as $v) {
110 if ($params['option_amount'][$v]) {
111 $defaultArray[$v] = 1;
112 }
113 }
114 }
115 else {
116 if (!empty($params['default_option'])) {
117 $defaultArray[$params['default_option']] = 1;
118 }
119 }
120
121 for ($index = 1; $index <= $maxIndex; $index++) {
122 if (array_key_exists('option_amount', $params) &&
123 array_key_exists($index, $params['option_amount']) &&
124 (CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_label', $params)) || !empty($params['is_quick_config'])) &&
125 !CRM_Utils_System::isNull($params['option_amount'][$index])
126 ) {
127 $options = array(
128 'price_field_id' => $priceField->id,
129 'label' => trim($params['option_label'][$index]),
130 'name' => CRM_Utils_String::munge($params['option_label'][$index], '_', 64),
131 'amount' => CRM_Utils_Rule::cleanMoney(trim($params['option_amount'][$index])),
132 'count' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_count', $params), NULL),
133 'max_value' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_max_value', $params), NULL),
134 'description' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_description', $params), NULL),
135 'membership_type_id' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('membership_type_id', $params), NULL),
136 'weight' => $params['option_weight'][$index],
137 'is_active' => 1,
138 'is_default' => CRM_Utils_Array::value($params['option_weight'][$index], $defaultArray) ? $defaultArray[$params['option_weight'][$index]] : 0,
139 'membership_num_terms' => NULL,
140 );
141
142 if ($options['membership_type_id']) {
143 $options['membership_num_terms'] = CRM_Utils_Array::value($index, CRM_Utils_Array::value('membership_num_terms', $params), 1);
144 }
145
146 if (CRM_Utils_Array::value( $index, CRM_Utils_Array::value('option_financial_type_id', $params))) {
147 $options['financial_type_id'] = $params['option_financial_type_id'][$index];
148 } elseif (!empty($params['financial_type_id'])) {
149 $options['financial_type_id'] = $params['financial_type_id'];
150 }
151
152 if ($opIds = CRM_Utils_Array::value('option_id', $params)) {
153 if ($opId = CRM_Utils_Array::value($index, $opIds)) {
154 $optionsIds['id'] = $opId;
155 } else {
156 $optionsIds['id'] = NULL;
157 }
158 }
159 CRM_Price_BAO_PriceFieldValue::create($options, $optionsIds);
160 }
161 }
162
163 $transaction->commit();
164 return $priceField;
165 }
166
167 /**
168 * Takes a bunch of params that are needed to match certain criteria and
169 * retrieves the relevant objects. Typically the valid params are only
170 * contact_id. We'll tweak this function to be more full featured over a period
171 * of time. This is the inverse function of create. It also stores all the retrieved
172 * values in the default array
173 *
174 * @param array $params (reference ) an assoc array of name/value pairs
175 * @param array $defaults (reference ) an assoc array to hold the flattened values
176 *
177 * @return object CRM_Price_DAO_PriceField object
178 * @access public
179 * @static
180 */
181 static function retrieve(&$params, &$defaults) {
182 return CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceField', $params, $defaults);
183 }
184
185 /**
186 * update the is_active flag in the db
187 *
188 * @param int $id Id of the database record
189 * @param boolean $is_active Value we want to set the is_active field
190 *
191 * @return Object DAO object on sucess, null otherwise
192 *
193 * @access public
194 * @static
195 */
196 static function setIsActive($id, $is_active) {
197 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceField', $id, 'is_active', $is_active);
198 }
199
200 /**
201 * Get the field title.
202 *
203 * @param int $id id of field.
204 *
205 * @return string name
206 *
207 * @access public
208 * @static
209 *
210 */
211 public static function getTitle($id) {
212 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $id, 'label');
213 }
214
215 /**
216 * This function for building custom fields
217 *
218 * @param object $qf form object (reference)
219 * @param string $elementName name of the custom field
220 * @param boolean $inactiveNeeded
221 * @param boolean $useRequired true if required else false
222 * @param boolean $search true if used for search else false
223 * @param string $label label for custom field
224 *
225 * @access public
226 * @static
227 */
228 public static function addQuickFormElement(&$qf,
229 $elementName,
230 $fieldId,
231 $inactiveNeeded,
232 $useRequired = TRUE,
233 $label = NULL,
234 $fieldOptions = NULL,
235 $feezeOptions = array()
236 ) {
237
238 $field = new CRM_Price_DAO_PriceField();
239 $field->id = $fieldId;
240 if (!$field->find(TRUE)) {
241 /* FIXME: failure! */
242 return NULL;
243 }
244
245 $is_pay_later = 0;
246 if (isset($qf->_mode) && empty($qf->_mode)) {
247 $is_pay_later = 1;
248 }
249 elseif (isset($qf->_values)) {
250 $is_pay_later = CRM_Utils_Array::value( 'is_pay_later', $qf->_values);
251 }
252
253 $otherAmount = $qf->get('values');
254 $config = CRM_Core_Config::singleton();
255 $currencySymbol = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_Currency',$config->defaultCurrency,'symbol','name');
256 $qf->assign('currencySymbol', $currencySymbol);
257 // get currency name for price field and option attributes
258 $currencyName = $config->defaultCurrency;
259
260 if (!isset($label)) {
261 $label = (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') ? ts('Additional Contribution') : $field->label;
262 }
263
264 if ($field->name == 'contribution_amount') {
265 $qf->_contributionAmount = 1;
266 }
267
268 if (isset($qf->_online) && $qf->_online) {
269 $useRequired = FALSE;
270 }
271
272 $customOption = $fieldOptions;
273 if (!is_array($customOption)) {
274 $customOption = CRM_Price_BAO_PriceField::getOptions($field->id, $inactiveNeeded);
275 }
276
277 //use value field.
278 $valueFieldName = 'amount';
279 $seperator = '|';
280 switch ($field->html_type) {
281 case 'Text':
282 $optionKey = key($customOption);
283 $count = CRM_Utils_Array::value('count', $customOption[$optionKey], '');
284 $max_value = CRM_Utils_Array::value('max_value', $customOption[$optionKey], '');
285 $priceVal = implode($seperator, array($customOption[$optionKey][$valueFieldName], $count, $max_value));
286
287 $extra = array();
288 if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
289 foreach($fieldOptions as &$fieldOption) {
290 if ($fieldOption['name'] == 'other_amount') {
291 $fieldOption['label'] = $fieldOption['label'] . ' ' . $currencySymbol;
292 }
293 }
294 $qf->assign('priceset', $elementName);
295 $extra = array('onclick' => 'useAmountOther();');
296 }
297
298 if (!empty($qf->_membershipBlock) && !empty($qf->_quickConfig) && $field->name == 'other_amount' && empty($qf->_contributionAmount)) {
299 $useRequired = 0;
300 }
301 elseif (!empty($fieldOptions[$optionKey]['label'])) { //check for label.
302 $label = $fieldOptions[$optionKey]['label'];
303 }
304
305 $element = &$qf->add('text', $elementName, $label,
306 array_merge($extra,
307 array('price' => json_encode(array($optionKey, $priceVal)),
308 'size' => '4',
309 )
310 ),
311 $useRequired && $field->is_required
312 );
313 if ($is_pay_later) {
314 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
315 }
316
317 // CRM-6902
318 if (in_array($optionKey, $feezeOptions)) {
319 $element->freeze();
320 }
321
322 //CRM-10117
323 if (!empty($qf->_quickConfig)) {
324 $message = ts('Please enter a valid amount.');
325 $type = 'money';
326 }
327 else {
328 $message = ts('%1 must be an integer (whole number).', array(1 => $label));
329 $type = 'positiveInteger';
330 }
331 // integers will have numeric rule applied to them.
332 $qf->addRule($elementName, $message, $type);
333 break;
334
335 case 'Radio':
336 $choice = array();
337
338 if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
339 $qf->assign('contriPriceset', $elementName);
340 }
341
342 foreach ($customOption as $opId => $opt) {
343 if ($field->is_display_amounts) {
344 $opt['label'] = !empty($opt['label']) ? $opt['label'] : '';
345 $opt['label'] = '<span class="crm-price-amount-amount">' . CRM_Utils_Money::format($opt[$valueFieldName]) . '</span> <span class="crm-price-amount-label">' . $opt['label'] . '</span>';
346 }
347 $count = CRM_Utils_Array::value('count', $opt, '');
348 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
349 $priceVal = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
350 $extra = array('price' => json_encode(array($elementName, $priceVal)),
351 'data-amount' => $opt[$valueFieldName],
352 'data-currency' => $currencyName,
353 );
354 if (!empty($qf->_quickConfig) && $field->name == 'contribution_amount') {
355 $extra += array('onclick' => 'clearAmountOther();');
356 }
357 elseif (!empty($qf->_quickConfig) && $field->name == 'membership_amount') {
358 $extra += array(
359 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
360 'membership-type' => $opt['membership_type_id'],
361 );
362 $qf->assign('membershipFieldID',$field->id);
363 }
364
365 $choice[$opId] = $qf->createElement('radio', NULL, '', $opt['label'], $opt['id'], $extra);
366
367 if ($is_pay_later) {
368 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
369 }
370
371 // CRM-6902
372 if (in_array($opId, $feezeOptions)) {
373 $choice[$opId]->freeze();
374 }
375 }
376 if (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') {
377 $choice[] = $qf->createElement('radio', NULL, '', ts('No thank you'), '-1',
378 array(
379 'onclick' => 'clearAmountOther();',
380 )
381 );
382 }
383
384 if (!$field->is_required) {
385 // add "none" option
386 if (!empty($otherAmount['is_allow_other_amount']) && $field->name == 'contribution_amount') {
387 $none = ts('Other Amount');
388 }
389 elseif (!empty($qf->_membershipBlock) && empty($qf->_membershipBlock['is_required']) && $field->name == 'membership_amount') {
390 $none = ts('No thank you');
391 }
392 else {
393 $none = ts('- none -');
394 }
395
396 $choice[] = $qf->createElement('radio', NULL, '', $none, '0',
397 array('price' => json_encode(array($elementName, '0')))
398 );
399 }
400
401 $element = &$qf->addGroup($choice, $elementName, $label);
402
403 // make contribution field required for quick config when membership block is enabled
404 if (($field->name == 'membership_amount' || $field->name == 'contribution_amount')
405 && !empty($qf->_membershipBlock) && !$field->is_required) {
406 $useRequired = $field->is_required = TRUE;
407 }
408
409 if ($useRequired && $field->is_required) {
410 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
411 }
412 break;
413
414 case 'Select':
415 $selectOption = $allowedOptions = $priceVal = array();
416
417 foreach ($customOption as $opt) {
418 $count = CRM_Utils_Array::value('count', $opt, '');
419 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
420 $priceVal[$opt['id']] = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
421
422 if ($field->is_display_amounts) {
423 $opt['label'] .= '&nbsp;-&nbsp;';
424 $opt['label'] .= CRM_Utils_Money::format($opt[$valueFieldName]);
425 }
426 $selectOption[$opt['id']] = $opt['label'];
427
428 if (!in_array($opt['id'], $feezeOptions)) {
429 $allowedOptions[] = $opt['id'];
430 }
431 if ($is_pay_later) {
432 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
433 }
434 }
435 $element = &$qf->add('select', $elementName, $label,
436 array(
437 '' => ts('- select -')) + $selectOption,
438 $useRequired && $field->is_required,
439 array('price' => json_encode($priceVal))
440 );
441
442 // CRM-6902
443 $button = substr($qf->controller->getButtonName(), -4);
444 if (!empty($feezeOptions) && $button != 'skip') {
445 $qf->addRule($elementName, ts('Sorry, this option is currently sold out.'), 'regex', "/" . implode('|', $allowedOptions) . "/");
446 }
447 break;
448
449 case 'CheckBox':
450
451 $check = array();
452 foreach ($customOption as $opId => $opt) {
453 $count = CRM_Utils_Array::value('count', $opt, '');
454 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
455 $priceVal = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
456
457 if ($field->is_display_amounts) {
458 $opt['label'] .= '&nbsp;-&nbsp;';
459 $opt['label'] .= CRM_Utils_Money::format($opt[$valueFieldName]);
460 }
461 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
462 array('price' => json_encode(array($opt['id'], $priceVal)),
463 'data-amount' => $opt[$valueFieldName],
464 'data-currency' => $currencyName,
465 )
466 );
467 if ($is_pay_later) {
468 $txtcheck[$opId] =& $qf->createElement( 'text', $opId, $opt['label'], array( 'size' => '4' ) );
469 $qf->addGroup($txtcheck, 'txt-'.$elementName, $label);
470 }
471 // CRM-6902
472 if (in_array($opId, $feezeOptions)) {
473 $check[$opId]->freeze();
474 }
475 }
476 $element = &$qf->addGroup($check, $elementName, $label);
477 if ($useRequired && $field->is_required) {
478 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
479 }
480 break;
481 }
482 if (isset($qf->_online) && $qf->_online) {
483 $element->freeze();
484 }
485 }
486
487 /**
488 * Retrieve a list of options for the specified field
489 *
490 * @param int $fieldId price field ID
491 * @param bool $inactiveNeeded include inactive options
492 * @param bool $reset ignore stored values\
493 *
494 * @return array array of options
495 */
496 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE) {
497 static $options = array();
498
499 if ($reset || empty($options[$fieldId])) {
500 $values = array();
501 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
502 $options[$fieldId] = $values;
503 }
504
505 return $options[$fieldId];
506 }
507
508 public static function getOptionId($optionLabel, $fid) {
509 if (!$optionLabel || !$fid) {
510 return;
511 }
512
513 $optionGroupName = "civicrm_price_field.amount.{$fid}";
514
515 $query = "
516 SELECT
517 option_value.id as id
518 FROM
519 civicrm_option_value option_value,
520 civicrm_option_group option_group
521 WHERE
522 option_group.name = %1
523 AND option_group.id = option_value.option_group_id
524 AND option_value.label = %2";
525
526 $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($optionGroupName, 'String'), 2 => array($optionLabel, 'String')));
527
528 while ($dao->fetch()) {
529 return $dao->id;
530 }
531 }
532
533 /**
534 * Delete the price set field.
535 *
536 * @param int $id Field Id
537 *
538 * @return boolean
539 *
540 * @access public
541 * @static
542 *
543 */
544 public static function deleteField($id) {
545 $field = new CRM_Price_DAO_PriceField();
546 $field->id = $id;
547
548 if ($field->find(TRUE)) {
549 // delete the options for this field
550 CRM_Price_BAO_PriceFieldValue::deleteValues($id);
551
552 // reorder the weight before delete
553 $fieldValues = array('price_set_id' => $field->price_set_id);
554
555 CRM_Utils_Weight::delWeight('CRM_Price_DAO_PriceField', $field->id, $fieldValues);
556
557 // now delete the field
558 return $field->delete();
559 }
560
561 return NULL;
562 }
563
564 static function &htmlTypes() {
565 static $htmlTypes = NULL;
566 if (!$htmlTypes) {
567 $htmlTypes = array(
568 'Text' => ts('Text / Numeric Quantity'),
569 'Select' => ts('Select'),
570 'Radio' => ts('Radio'),
571 'CheckBox' => ts('CheckBox'),
572 );
573 }
574 return $htmlTypes;
575 }
576
577 /**
578 * Validate the priceset
579 *
580 * @param int $priceSetId, array $fields
581 *
582 * retrun the error string
583 *
584 * @access public
585 * @static
586 *
587 */
588
589 public static function priceSetValidation($priceSetId, $fields, &$error, $allowNoneSelection = FALSE) {
590 // check for at least one positive
591 // amount price field should be selected.
592 $priceField = new CRM_Price_DAO_PriceField();
593 $priceField->price_set_id = $priceSetId;
594 $priceField->find();
595
596 $priceFields = array();
597
598 if ($allowNoneSelection) {
599 $noneSelectedPriceFields = array();
600 }
601
602 while ($priceField->fetch()) {
603 $key = "price_{$priceField->id}";
604
605 if ($allowNoneSelection) {
606 if (array_key_exists($key, $fields)) {
607 if ($fields[$key] == 0 && !$priceField->is_required) {
608 $noneSelectedPriceFields[] = $priceField->id;
609 }
610 }
611 }
612
613 if (!empty($fields[$key])) {
614 $priceFields[$priceField->id] = $fields[$key];
615 }
616 }
617
618 if (!empty($priceFields)) {
619 // we should has to have positive amount.
620 $sql = "
621 SELECT id, html_type
622 FROM civicrm_price_field
623 WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
624 $fieldDAO = CRM_Core_DAO::executeQuery($sql);
625 $htmlTypes = array();
626 while ($fieldDAO->fetch()) {
627 $htmlTypes[$fieldDAO->id] = $fieldDAO->html_type;
628 }
629
630 $selectedAmounts = array();
631
632 foreach ($htmlTypes as $fieldId => $type) {
633 $options = array();
634 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $options);
635
636 if (empty($options)) {
637 continue;
638 }
639
640 if ($type == 'Text') {
641 foreach ($options as $opId => $option) {
642 $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount'];
643 break;
644 }
645 }
646 elseif (is_array($fields["price_{$fieldId}"])) {
647 foreach (array_keys($fields["price_{$fieldId}"]) as $opId) {
648 $selectedAmounts[$opId] = $options[$opId]['amount'];
649 }
650 }
651 elseif (in_array($fields["price_{$fieldId}"], array_keys($options))) {
652 $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount'];
653 }
654 }
655
656 list($componentName) = explode(':', $fields['_qf_default']);
657 // now we have all selected amount in hand.
658 $totalAmount = array_sum($selectedAmounts);
659 if ($totalAmount < 0) {
660 $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', array(1 => $componentName));
661 }
662 }
663 else {
664 if ($allowNoneSelection) {
665 if (empty($noneSelectedPriceFields)) {
666 $error['_qf_default'] = ts('Please select at least one option from price set.');
667 }
668 } else {
669 $error['_qf_default'] = ts('Please select at least one option from price set.');
670 }
671 }
672 }
673 }
674