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