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