Merge pull request #21135 from seamuslee001/dev_core_1618
[civicrm-core.git] / CRM / Core / OptionGroup.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Core_OptionGroup {
18 public static $_values = [];
19 public static $_cache = [];
20
21 /**
22 * $_domainIDGroups array maintains the list of option groups for whom
23 * domainID is to be considered.
24 * @var array
25 */
26 public static $_domainIDGroups = [
27 'from_email_address',
28 'grant_type',
29 ];
30
31 /**
32 * @param CRM_Core_DAO $dao
33 * @param bool $flip
34 * @param bool $grouping
35 * @param bool $localize
36 * @param string $valueColumnName
37 *
38 * @return array
39 */
40 public static function &valuesCommon(
41 $dao, $flip = FALSE, $grouping = FALSE,
42 $localize = FALSE, $valueColumnName = 'label'
43 ) {
44 self::$_values = [];
45
46 while ($dao->fetch()) {
47 if ($flip) {
48 if ($grouping) {
49 self::$_values[$dao->value] = $dao->grouping;
50 }
51 else {
52 self::$_values[$dao->{$valueColumnName}] = $dao->value;
53 }
54 }
55 else {
56 if ($grouping) {
57 self::$_values[$dao->{$valueColumnName}] = $dao->grouping;
58 }
59 else {
60 self::$_values[$dao->value] = $dao->{$valueColumnName};
61 }
62 }
63 }
64 if ($localize) {
65 $i18n = CRM_Core_I18n::singleton();
66 $i18n->localizeArray(self::$_values);
67 }
68 return self::$_values;
69 }
70
71 /**
72 * This function retrieves all the values for the specific option group by name
73 * this is primarily used to create various html based form elements
74 * (radio, select, checkbox etc). OptionGroups for most cases have the
75 * 'label' in the label column and the 'id' or 'name' in the value column
76 *
77 * @param string $name
78 * name of the option group.
79 * @param bool $flip
80 * results are return in id => label format if false.
81 * if true, the results are reversed
82 * @param bool $grouping
83 * if true, return the value in 'grouping' column.
84 * @param bool $localize
85 * if true, localize the results before returning.
86 * @param string $condition
87 * add another condition to the sql query.
88 * @param string $labelColumnName
89 * the column to use for 'label'.
90 * @param bool $onlyActive
91 * return only the action option values.
92 * @param bool $fresh
93 * ignore cache entries and go back to DB.
94 * @param string $keyColumnName
95 * the column to use for 'key'.
96 * @param string $orderBy
97 * the column to use for ordering.
98 *
99 * @return array
100 * The values as specified by the params
101 */
102 public static function &values(
103 $name, $flip = FALSE, $grouping = FALSE,
104 $localize = FALSE, $condition = NULL,
105 $labelColumnName = 'label', $onlyActive = TRUE, $fresh = FALSE, $keyColumnName = 'value',
106 $orderBy = 'weight'
107 ) {
108 $cache = CRM_Utils_Cache::singleton();
109 if (in_array($name, self::$_domainIDGroups)) {
110 $cacheKey = self::createCacheKey($name, CRM_Core_I18n::getLocale(), $flip, $grouping, $localize, $condition, $labelColumnName, $onlyActive, $keyColumnName, $orderBy, CRM_Core_Config::domainID());
111 }
112 else {
113 $cacheKey = self::createCacheKey($name, CRM_Core_I18n::getLocale(), $flip, $grouping, $localize, $condition, $labelColumnName, $onlyActive, $keyColumnName, $orderBy);
114 }
115
116 if (!$fresh) {
117 // Fetch from static var
118 if (array_key_exists($cacheKey, self::$_cache)) {
119 return self::$_cache[$cacheKey];
120 }
121 // Fetch from main cache
122 self::$_cache[$cacheKey] = $cache->get($cacheKey);
123 if (self::$_cache[$cacheKey] !== NULL) {
124 return self::$_cache[$cacheKey];
125 }
126 }
127
128 $query = "
129 SELECT v.{$labelColumnName} as {$labelColumnName} ,v.{$keyColumnName} as value, v.grouping as `grouping`
130 FROM civicrm_option_value v,
131 civicrm_option_group g
132 WHERE v.option_group_id = g.id
133 AND g.name = %1
134 AND g.is_active = 1 ";
135
136 if ($onlyActive) {
137 $query .= " AND v.is_active = 1 ";
138 // Only show options for enabled components
139 $componentClause = ' v.component_id IS NULL ';
140 $enabledComponents = CRM_Core_Config::singleton()->enableComponents;
141 if ($enabledComponents) {
142 $enabledComponents = '"' . implode('","', $enabledComponents) . '"';
143 $componentClause .= " OR v.component_id IN (SELECT id FROM civicrm_component WHERE name IN ($enabledComponents)) ";
144 }
145 $query .= " AND ($componentClause) ";
146 }
147 if (in_array($name, self::$_domainIDGroups)) {
148 $query .= " AND v.domain_id = " . CRM_Core_Config::domainID();
149 }
150
151 if ($condition) {
152 $query .= $condition;
153 }
154
155 $query .= " ORDER BY v.{$orderBy}";
156
157 $p = [1 => [$name, 'String']];
158 $dao = CRM_Core_DAO::executeQuery($query, $p);
159
160 $var = self::valuesCommon($dao, $flip, $grouping, $localize, $labelColumnName);
161
162 // call option value hook
163 CRM_Utils_Hook::optionValues($var, $name);
164
165 self::$_cache[$cacheKey] = $var;
166 $cache->set($cacheKey, $var);
167
168 return $var;
169 }
170
171 /**
172 * Counterpart to values() which removes the item from the cache
173 *
174 * @param string $name
175 * @param $flip
176 * @param $grouping
177 * @param $localize
178 * @param $condition
179 * @param string $labelColumnName
180 * @param $onlyActive
181 * @param string $keyColumnName
182 */
183 protected static function flushValues($name, $flip, $grouping, $localize, $condition, $labelColumnName, $onlyActive, $keyColumnName = 'value') {
184 $cacheKey = self::createCacheKey($name, CRM_Core_I18n::getLocale(), $flip, $grouping, $localize, $condition, $labelColumnName, $onlyActive, $keyColumnName);
185 $cache = CRM_Utils_Cache::singleton();
186 $cache->delete($cacheKey);
187 unset(self::$_cache[$cacheKey]);
188 }
189
190 /**
191 * @return string
192 */
193 protected static function createCacheKey($id) {
194 return "CRM_OG_" . preg_replace('/[^a-zA-Z0-9]/', '', $id) . '_' . md5(serialize(func_get_args()));
195 }
196
197 /**
198 * This function retrieves all the values for the specific option group by id.
199 * this is primarily used to create various html based form elements
200 * (radio, select, checkbox etc). OptionGroups for most cases have the
201 * 'label' in the label column and the 'id' or 'name' in the value column
202 *
203 * @param int $id
204 * id of the option group.
205 * @param bool $flip
206 * results are return in id => label format if false.
207 * if true, the results are reversed
208 * @param bool $grouping
209 * if true, return the value in 'grouping' column.
210 * @param bool $localize
211 * if true, localize the results before returning.
212 * @param string $labelColumnName
213 * the column to use for 'label'.
214 * @param bool $onlyActive
215 * @param bool $fresh
216 *
217 * @return array
218 * Array of values as specified by the above params
219 * @void
220 */
221 public static function &valuesByID($id, $flip = FALSE, $grouping = FALSE, $localize = FALSE, $labelColumnName = 'label', $onlyActive = TRUE, $fresh = FALSE) {
222 $cacheKey = self::createCacheKey($id, CRM_Core_I18n::getLocale(), $flip, $grouping, $localize, $labelColumnName, $onlyActive);
223
224 $cache = CRM_Utils_Cache::singleton();
225 if (!$fresh) {
226 self::$_cache[$cacheKey] = $cache->get($cacheKey);
227 if (self::$_cache[$cacheKey] !== NULL) {
228 return self::$_cache[$cacheKey];
229 }
230 }
231 $query = "
232 SELECT v.{$labelColumnName} as {$labelColumnName} ,v.value as value, v.grouping as `grouping`
233 FROM civicrm_option_value v,
234 civicrm_option_group g
235 WHERE v.option_group_id = g.id
236 AND g.id = %1
237 AND g.is_active = 1
238 ";
239 if ($onlyActive) {
240 $query .= " AND v.is_active = 1 ";
241 }
242 $query .= " ORDER BY v.weight, v.label";
243
244 $p = [1 => [$id, 'Integer']];
245 $dao = CRM_Core_DAO::executeQuery($query, $p);
246
247 $var = self::valuesCommon($dao, $flip, $grouping, $localize, $labelColumnName);
248 $cache->set($cacheKey, $var);
249
250 return $var;
251 }
252
253 /**
254 * Lookup titles OR ids for a set of option_value populated fields. The
255 * retrieved value is assigned a new field name by id or id's by title
256 * (each within a specified option_group).
257 *
258 * @param array $params
259 * Reference array of values submitted by the form. Based on.
260 * $flip, creates new elements in $params for each field in
261 * the $names array.
262 * If $flip = false, adds root field name => title
263 * If $flip = true, adds actual field name => id
264 *
265 * @param array $names
266 * Array of field names we want transformed.
267 * Array key = 'postName' (field name submitted by form in $params).
268 * Array value = array('newName' => $newName, 'groupName' => $groupName).
269 *
270 * @param bool $flip
271 */
272 public static function lookupValues(&$params, $names, $flip = FALSE) {
273 foreach ($names as $postName => $value) {
274 // See if $params field is in $names array (i.e. is a value that we need to lookup)
275 if ($postalName = CRM_Utils_Array::value($postName, $params)) {
276 $postValues = [];
277 // params[$postName] may be a Ctrl+A separated value list
278 if (is_string($postalName) &&
279 strpos($postalName, CRM_Core_DAO::VALUE_SEPARATOR) == FALSE
280 ) {
281 // eliminate the ^A frm the beginning and end if present
282 if (substr($postalName, 0, 1) == CRM_Core_DAO::VALUE_SEPARATOR) {
283 $params[$postName] = substr($params[$postName], 1, -1);
284 }
285 $postValues = explode(CRM_Core_DAO::VALUE_SEPARATOR, $params[$postName]);
286 }
287 elseif (is_array($postalName)) {
288 $postValues = $postalName;
289 }
290 $newValue = [];
291 foreach ($postValues as $postValue) {
292 if (!$postValue) {
293 continue;
294 }
295
296 if ($flip) {
297 $p = [1 => [$postValue, 'String']];
298 $lookupBy = 'v.label= %1';
299 $select = "v.value";
300 }
301 else {
302 $p = [1 => [$postValue, 'Integer']];
303 $lookupBy = 'v.value = %1';
304 $select = "v.label";
305 }
306
307 $p[2] = [$value['groupName'], 'String'];
308 $query = "
309 SELECT $select
310 FROM civicrm_option_value v,
311 civicrm_option_group g
312 WHERE v.option_group_id = g.id
313 AND g.name = %2
314 AND $lookupBy";
315
316 $newValue[] = CRM_Core_DAO::singleValueQuery($query, $p);
317 $newValue = str_replace(',', '_', $newValue);
318 }
319 $params[$value['newName']] = implode(', ', $newValue);
320 }
321 }
322 }
323
324 /**
325 * @deprecated - use CRM_Core_PseudoConstant::getLabel
326 *
327 * @param string $groupName
328 * @param $value
329 * @param bool $onlyActiveValue
330 *
331 * @return null
332 */
333 public static function getLabel($groupName, $value, $onlyActiveValue = TRUE) {
334 CRM_Core_Error::deprecatedFunctionWarning('CRM_Core_PseudoConstant::getLabel');
335 if (empty($groupName) ||
336 empty($value)
337 ) {
338 return NULL;
339 }
340
341 $query = "
342 SELECT v.label as label ,v.value as value
343 FROM civicrm_option_value v,
344 civicrm_option_group g
345 WHERE v.option_group_id = g.id
346 AND g.name = %1
347 AND g.is_active = 1
348 AND v.value = %2
349 ";
350 if ($onlyActiveValue) {
351 $query .= " AND v.is_active = 1 ";
352 }
353 $p = [
354 1 => [$groupName, 'String'],
355 2 => [$value, 'Integer'],
356 ];
357 $dao = CRM_Core_DAO::executeQuery($query, $p);
358 if ($dao->fetch()) {
359 return $dao->label;
360 }
361 return NULL;
362 }
363
364 /**
365 * @deprecated
366 *
367 * This function is not cached.
368 *
369 * @param string $groupName
370 * @param $label
371 * @param string $labelField
372 * @param string $labelType
373 * @param string $valueField
374 *
375 * @return null
376 */
377 public static function getValue(
378 $groupName,
379 $label,
380 $labelField = 'label',
381 $labelType = 'String',
382 $valueField = 'value'
383 ) {
384 if (empty($label)) {
385 return NULL;
386 }
387
388 CRM_Core_Error::deprecatedFunctionWarning('CRM_Core_PseudoConstant::getKey');
389
390 $query = "
391 SELECT v.label as label ,v.{$valueField} as value
392 FROM civicrm_option_value v,
393 civicrm_option_group g
394 WHERE v.option_group_id = g.id
395 AND g.name = %1
396 AND v.is_active = 1
397 AND g.is_active = 1
398 AND v.$labelField = %2
399 ";
400
401 $p = [
402 1 => [$groupName, 'String'],
403 2 => [$label, $labelType],
404 ];
405 $dao = CRM_Core_DAO::executeQuery($query, $p);
406 if ($dao->fetch()) {
407 return $dao->value;
408 }
409 return NULL;
410 }
411
412 /**
413 * Get option_value.value from default option_value row for an option group
414 *
415 * @param string $groupName
416 * The name of the option group.
417 *
418 *
419 * @return string
420 * the value from the row where is_default = true
421 */
422 public static function getDefaultValue($groupName) {
423 if (empty($groupName)) {
424 return NULL;
425 }
426 $query = "
427 SELECT v.value
428 FROM civicrm_option_value v,
429 civicrm_option_group g
430 WHERE v.option_group_id = g.id
431 AND g.name = %1
432 AND v.is_active = 1
433 AND g.is_active = 1
434 AND v.is_default = 1
435 ";
436 if (in_array($groupName, self::$_domainIDGroups)) {
437 $query .= " AND v.domain_id = " . CRM_Core_Config::domainID();
438 }
439
440 $p = [1 => [$groupName, 'String']];
441 return CRM_Core_DAO::singleValueQuery($query, $p);
442 }
443
444 /**
445 * Creates a new option group with the passed in values.
446 *
447 * @param string $groupName
448 * The name of the option group - make sure there is no conflict.
449 * @param array $values
450 * The associative array that has information on the option values.
451 * the keys of this array are:
452 * string 'title' (required)
453 * string 'value' (required)
454 * string 'name' (optional)
455 * string 'description' (optional)
456 * int 'weight' (optional) - the order in which the value are displayed
457 * bool 'is_default' (optional) - is this the default one to display when rendered in form
458 * bool 'is_active' (optional) - should this element be rendered
459 * @param int $defaultID
460 * (reference) - the option value ID of the default element (if set) is returned else 'null'.
461 * @param null $groupTitle
462 * The optional label of the option group else set to group name.
463 *
464 *
465 * @return int
466 * the option group ID
467 */
468 public static function createAssoc($groupName, &$values, &$defaultID, $groupTitle = NULL) {
469 // @TODO: This causes a problem in multilingual
470 // (https://github.com/civicrm/civicrm-core/pull/17228), but is needed in
471 // order to be able to remove currencies once added.
472 if (!CRM_Core_I18n::isMultiLingual()) {
473 self::deleteAssoc($groupName);
474 }
475 if (!empty($values)) {
476 $group = new CRM_Core_DAO_OptionGroup();
477 $group->name = $groupName;
478 $group->find(TRUE);
479 $group->title = empty($groupTitle) ? $groupName : $groupTitle;
480 $group->is_reserved = 1;
481 $group->is_active = 1;
482 $group->save();
483
484 foreach ($values as $v) {
485 $value = new CRM_Core_DAO_OptionValue();
486 $value->option_group_id = $group->id;
487 $value->value = $v['value'];
488 $value->find(TRUE);
489 $value->label = $v['label'];
490 $value->name = $v['name'] ?? NULL;
491 $value->description = $v['description'] ?? NULL;
492 $value->weight = $v['weight'] ?? NULL;
493 $value->is_default = $v['is_default'] ?? NULL;
494 $value->is_active = $v['is_active'] ?? NULL;
495 $value->save();
496
497 if ($value->is_default) {
498 $defaultID = $value->id;
499 }
500 }
501 }
502 else {
503 return $defaultID = 'null';
504 }
505
506 return $group->id;
507 }
508
509 /**
510 * @param string $groupName
511 * @param $values
512 * @param bool $flip
513 * @param string $field
514 *
515 * @deprecated
516 */
517 public static function getAssoc($groupName, &$values, $flip = FALSE, $field = 'name') {
518 CRM_Core_Error::deprecatedFunctionWarning('unused function');
519 $query = "
520 SELECT v.id as amount_id, v.value, v.label, v.name, v.description, v.weight
521 FROM civicrm_option_group g,
522 civicrm_option_value v
523 WHERE g.id = v.option_group_id
524 AND g.$field = %1
525 ORDER BY v.weight
526 ";
527 $params = [1 => [$groupName, 'String']];
528 $dao = CRM_Core_DAO::executeQuery($query, $params);
529
530 $fields = ['value', 'label', 'name', 'description', 'amount_id', 'weight'];
531 if ($flip) {
532 $values = [];
533 }
534 else {
535 foreach ($fields as $field) {
536 $values[$field] = [];
537 }
538 }
539 $index = 1;
540
541 while ($dao->fetch()) {
542 if ($flip) {
543 $value = [];
544 foreach ($fields as $field) {
545 $value[$field] = $dao->$field;
546 }
547 $values[$dao->amount_id] = $value;
548 }
549 else {
550 foreach ($fields as $field) {
551 $values[$field][$index] = $dao->$field;
552 }
553 $index++;
554 }
555 }
556 }
557
558 /**
559 * @param string $groupName
560 * @param string $operator
561 */
562 public static function deleteAssoc($groupName, $operator = "=") {
563 $query = "
564 DELETE g, v
565 FROM civicrm_option_group g,
566 civicrm_option_value v
567 WHERE g.id = v.option_group_id
568 AND g.name {$operator} %1";
569
570 $params = [1 => [$groupName, 'String']];
571
572 $dao = CRM_Core_DAO::executeQuery($query, $params);
573 }
574
575 /**
576 * @param string $groupName
577 * @param $fieldValue
578 * @param string $field
579 * @param string $fieldType
580 * @param bool $active
581 * @param bool $localize
582 * if true, localize the results before returning.
583 *
584 * @return array
585 */
586 public static function getRowValues(
587 $groupName, $fieldValue, $field = 'name',
588 $fieldType = 'String', $active = TRUE, $localize = FALSE
589 ) {
590 $query = "
591 SELECT v.id, v.label, v.value, v.name, v.weight, v.description
592 FROM civicrm_option_value v,
593 civicrm_option_group g
594 WHERE v.option_group_id = g.id
595 AND g.name = %1
596 AND g.is_active = 1
597 AND v.$field = %2
598 ";
599
600 if ($active) {
601 $query .= " AND v.is_active = 1";
602 }
603
604 $p = [
605 1 => [$groupName, 'String'],
606 2 => [$fieldValue, $fieldType],
607 ];
608 $dao = CRM_Core_DAO::executeQuery($query, $p);
609 $row = [];
610
611 if ($dao->fetch()) {
612 foreach ([
613 'id',
614 'name',
615 'value',
616 'label',
617 'weight',
618 'description',
619 ] as $fld) {
620 $row[$fld] = $dao->$fld;
621 if ($localize && in_array($fld, ['label', 'description'])) {
622 $row[$fld] = ts($row[$fld]);
623 }
624 }
625 }
626
627 return $row;
628 }
629
630 /**
631 * Wrapper for calling values with fresh set to true to empty the given value.
632 *
633 * Since there appears to be some inconsistency
634 * (@todo remove inconsistency) around the pseudoconstant operations
635 * (for example CRM_Contribution_Pseudoconstant::paymentInstrument doesn't specify isActive
636 * which is part of the cache key
637 * will do a couple of variations & aspire to someone cleaning it up later
638 *
639 * @param string $name
640 * @param array $params
641 */
642 public static function flush($name, $params = []) {
643 $defaults = [
644 'flip' => FALSE,
645 'grouping' => FALSE,
646 'localize' => FALSE,
647 'condition' => NULL,
648 'labelColumnName' => 'label',
649 ];
650
651 $params = array_merge($defaults, $params);
652 self::flushValues(
653 $name,
654 $params['flip'],
655 $params['grouping'],
656 $params['localize'],
657 $params['condition'],
658 $params['labelColumnName'],
659 TRUE,
660 TRUE
661 );
662 self::flushValues(
663 $name,
664 $params['flip'],
665 $params['grouping'],
666 $params['localize'],
667 $params['condition'],
668 $params['labelColumnName'],
669 FALSE,
670 TRUE
671 );
672 }
673
674 /**
675 * Flush all the places where option values are cached.
676 *
677 * Note that this is called from CRM_Core_PseudoConstant::flush() so we should resist
678 * the intuitive urge to flush that class.
679 */
680 public static function flushAll() {
681 self::$_values = [];
682 self::$_cache = [];
683 CRM_Utils_Cache::singleton()->flush();
684 }
685
686 }