Merge branch '4.4' into master
[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 seperate membership payment is used with quick config priceset then change the other amount label
299 if (!empty($qf->_membershipBlock) && !empty($qf->_quickConfig) && $field->name == 'other_amount' && empty($qf->_contributionAmount)) {
300 $label = ts('Additional Contribution');
301 $useRequired = 0;
302 }
303 elseif (!empty($fieldOptions[$optionKey]['label'])) { //check for label.
304 $label = $fieldOptions[$optionKey]['label'];
305 }
306
307 $element = &$qf->add('text', $elementName, $label,
308 array_merge($extra,
309 array('price' => json_encode(array($optionKey, $priceVal)),
310 'size' => '4',
311 )
312 ),
313 $useRequired && $field->is_required
314 );
315 if ($is_pay_later) {
316 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
317 }
318
319 // CRM-6902
320 if (in_array($optionKey, $feezeOptions)) {
321 $element->freeze();
322 }
323
324 //CRM-10117
325 if (!empty($qf->_quickConfig)) {
326 $message = ts('Please enter a valid amount.');
327 $type = 'money';
328 }
329 else {
330 $message = ts('%1 must be an integer (whole number).', array(1 => $label));
331 $type = 'positiveInteger';
332 }
333 // integers will have numeric rule applied to them.
334 $qf->addRule($elementName, $message, $type);
335 break;
336
337 case 'Radio':
338 $choice = array();
339
340 if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
341 $qf->assign('contriPriceset', $elementName);
342 }
343
344 foreach ($customOption as $opId => $opt) {
345 if ($field->is_display_amounts) {
346 $opt['label'] = !empty($opt['label']) ? $opt['label'] : '';
347 $opt['label'] = '<span class="crm-price-amount-amount">' . CRM_Utils_Money::format($opt[$valueFieldName]) . '</span> <span class="crm-price-amount-label">' . $opt['label'] . '</span>';
348 }
349 $count = CRM_Utils_Array::value('count', $opt, '');
350 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
351 $priceVal = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
352 $extra = array('price' => json_encode(array($elementName, $priceVal)),
353 'data-amount' => $opt[$valueFieldName],
354 'data-currency' => $currencyName,
355 );
356 if (!empty($qf->_quickConfig) && $field->name == 'contribution_amount') {
357 $extra += array('onclick' => 'clearAmountOther();');
358 }
359 elseif (!empty($qf->_quickConfig) && $field->name == 'membership_amount') {
360 $extra += array(
361 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
362 'membership-type' => $opt['membership_type_id'],
363 );
364 $qf->assign('membershipFieldID',$field->id);
365 }
366
367 $choice[$opId] = $qf->createElement('radio', NULL, '', $opt['label'], $opt['id'], $extra);
368
369 if ($is_pay_later) {
370 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
371 }
372
373 // CRM-6902
374 if (in_array($opId, $feezeOptions)) {
375 $choice[$opId]->freeze();
376 }
377 }
378 if (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') {
379 $choice[] = $qf->createElement('radio', NULL, '', ts('No thank you'), '-1',
380 array(
381 'onclick' => 'clearAmountOther();',
382 )
383 );
384 }
385
386 if (!$field->is_required) {
387 // add "none" option
388 if (!empty($otherAmount['is_allow_other_amount']) && $field->name == 'contribution_amount') {
389 $none = ts('Other Amount');
390 }
391 elseif (!empty($qf->_membershipBlock) && empty($qf->_membershipBlock['is_required']) && $field->name == 'membership_amount') {
392 $none = ts('No thank you');
393 }
394 else {
395 $none = ts('- none -');
396 }
397
398 $choice[] = $qf->createElement('radio', NULL, '', $none, '0',
399 array('price' => json_encode(array($elementName, '0')))
400 );
401 }
402
403 $element = &$qf->addGroup($choice, $elementName, $label);
404
405 // make contribution field required for quick config when membership block is enabled
406 if (($field->name == 'membership_amount' || $field->name == 'contribution_amount')
407 && !empty($qf->_membershipBlock) && !$field->is_required) {
408 $useRequired = $field->is_required = TRUE;
409 }
410
411 if ($useRequired && $field->is_required) {
412 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
413 }
414 break;
415
416 case 'Select':
417 $selectOption = $allowedOptions = $priceVal = array();
418
419 foreach ($customOption as $opt) {
420 $count = CRM_Utils_Array::value('count', $opt, '');
421 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
422 $priceVal[$opt['id']] = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
423
424 if ($field->is_display_amounts) {
425 $opt['label'] .= '&nbsp;-&nbsp;';
426 $opt['label'] .= CRM_Utils_Money::format($opt[$valueFieldName]);
427 }
428 $selectOption[$opt['id']] = $opt['label'];
429
430 if (!in_array($opt['id'], $feezeOptions)) {
431 $allowedOptions[] = $opt['id'];
432 }
433 if ($is_pay_later) {
434 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
435 }
436 }
437 $element = &$qf->add('select', $elementName, $label,
438 array(
439 '' => ts('- select -')) + $selectOption,
440 $useRequired && $field->is_required,
441 array('price' => json_encode($priceVal))
442 );
443
444 // CRM-6902
445 $button = substr($qf->controller->getButtonName(), -4);
446 if (!empty($feezeOptions) && $button != 'skip') {
447 $qf->addRule($elementName, ts('Sorry, this option is currently sold out.'), 'regex', "/" . implode('|', $allowedOptions) . "/");
448 }
449 break;
450
451 case 'CheckBox':
452
453 $check = array();
454 foreach ($customOption as $opId => $opt) {
455 $count = CRM_Utils_Array::value('count', $opt, '');
456 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
457 $priceVal = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
458
459 if ($field->is_display_amounts) {
460 $opt['label'] .= '&nbsp;-&nbsp;';
461 $opt['label'] .= CRM_Utils_Money::format($opt[$valueFieldName]);
462 }
463 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
464 array('price' => json_encode(array($opt['id'], $priceVal)),
465 'data-amount' => $opt[$valueFieldName],
466 'data-currency' => $currencyName,
467 )
468 );
469 if ($is_pay_later) {
470 $txtcheck[$opId] =& $qf->createElement( 'text', $opId, $opt['label'], array( 'size' => '4' ) );
471 $qf->addGroup($txtcheck, 'txt-'.$elementName, $label);
472 }
473 // CRM-6902
474 if (in_array($opId, $feezeOptions)) {
475 $check[$opId]->freeze();
476 }
477 }
478 $element = &$qf->addGroup($check, $elementName, $label);
479 if ($useRequired && $field->is_required) {
480 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
481 }
482 break;
483 }
484 if (isset($qf->_online) && $qf->_online) {
485 $element->freeze();
486 }
487 }
488
489 /**
490 * Retrieve a list of options for the specified field
491 *
492 * @param int $fieldId price field ID
493 * @param bool $inactiveNeeded include inactive options
494 * @param bool $reset ignore stored values\
495 *
496 * @return array array of options
497 */
498 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE) {
499 static $options = array();
500
501 if ($reset || empty($options[$fieldId])) {
502 $values = array();
503 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
504 $options[$fieldId] = $values;
505 }
506
507 return $options[$fieldId];
508 }
509
510 public static function getOptionId($optionLabel, $fid) {
511 if (!$optionLabel || !$fid) {
512 return;
513 }
514
515 $optionGroupName = "civicrm_price_field.amount.{$fid}";
516
517 $query = "
518 SELECT
519 option_value.id as id
520 FROM
521 civicrm_option_value option_value,
522 civicrm_option_group option_group
523 WHERE
524 option_group.name = %1
525 AND option_group.id = option_value.option_group_id
526 AND option_value.label = %2";
527
528 $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($optionGroupName, 'String'), 2 => array($optionLabel, 'String')));
529
530 while ($dao->fetch()) {
531 return $dao->id;
532 }
533 }
534
535 /**
536 * Delete the price set field.
537 *
538 * @param int $id Field Id
539 *
540 * @return boolean
541 *
542 * @access public
543 * @static
544 *
545 */
546 public static function deleteField($id) {
547 $field = new CRM_Price_DAO_PriceField();
548 $field->id = $id;
549
550 if ($field->find(TRUE)) {
551 // delete the options for this field
552 CRM_Price_BAO_PriceFieldValue::deleteValues($id);
553
554 // reorder the weight before delete
555 $fieldValues = array('price_set_id' => $field->price_set_id);
556
557 CRM_Utils_Weight::delWeight('CRM_Price_DAO_PriceField', $field->id, $fieldValues);
558
559 // now delete the field
560 return $field->delete();
561 }
562
563 return NULL;
564 }
565
566 static function &htmlTypes() {
567 static $htmlTypes = NULL;
568 if (!$htmlTypes) {
569 $htmlTypes = array(
570 'Text' => ts('Text / Numeric Quantity'),
571 'Select' => ts('Select'),
572 'Radio' => ts('Radio'),
573 'CheckBox' => ts('CheckBox'),
574 );
575 }
576 return $htmlTypes;
577 }
578
579 /**
580 * Validate the priceset
581 *
582 * @param int $priceSetId, array $fields
583 *
584 * retrun the error string
585 *
586 * @access public
587 * @static
588 *
589 */
590
591 public static function priceSetValidation($priceSetId, $fields, &$error, $allowNoneSelection = FALSE) {
592 // check for at least one positive
593 // amount price field should be selected.
594 $priceField = new CRM_Price_DAO_PriceField();
595 $priceField->price_set_id = $priceSetId;
596 $priceField->find();
597
598 $priceFields = array();
599
600 if ($allowNoneSelection) {
601 $noneSelectedPriceFields = array();
602 }
603
604 while ($priceField->fetch()) {
605 $key = "price_{$priceField->id}";
606
607 if ($allowNoneSelection) {
608 if (array_key_exists($key, $fields)) {
609 if ($fields[$key] == 0 && !$priceField->is_required) {
610 $noneSelectedPriceFields[] = $priceField->id;
611 }
612 }
613 }
614
615 if (!empty($fields[$key])) {
616 $priceFields[$priceField->id] = $fields[$key];
617 }
618 }
619
620 if (!empty($priceFields)) {
621 // we should has to have positive amount.
622 $sql = "
623 SELECT id, html_type
624 FROM civicrm_price_field
625 WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
626 $fieldDAO = CRM_Core_DAO::executeQuery($sql);
627 $htmlTypes = array();
628 while ($fieldDAO->fetch()) {
629 $htmlTypes[$fieldDAO->id] = $fieldDAO->html_type;
630 }
631
632 $selectedAmounts = array();
633
634 foreach ($htmlTypes as $fieldId => $type) {
635 $options = array();
636 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $options);
637
638 if (empty($options)) {
639 continue;
640 }
641
642 if ($type == 'Text') {
643 foreach ($options as $opId => $option) {
644 $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount'];
645 break;
646 }
647 }
648 elseif (is_array($fields["price_{$fieldId}"])) {
649 foreach (array_keys($fields["price_{$fieldId}"]) as $opId) {
650 $selectedAmounts[$opId] = $options[$opId]['amount'];
651 }
652 }
653 elseif (in_array($fields["price_{$fieldId}"], array_keys($options))) {
654 $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount'];
655 }
656 }
657
658 list($componentName) = explode(':', $fields['_qf_default']);
659 // now we have all selected amount in hand.
660 $totalAmount = array_sum($selectedAmounts);
661 if ($totalAmount < 0) {
662 $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', array(1 => $componentName));
663 }
664 }
665 else {
666 if ($allowNoneSelection) {
667 if (empty($noneSelectedPriceFields)) {
668 $error['_qf_default'] = ts('Please select at least one option from price set.');
669 }
670 } else {
671 $error['_qf_default'] = ts('Please select at least one option from price set.');
672 }
673 }
674 }
675 }
676