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