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