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