Merge pull request #24162 from colemanw/savedSearchLabel
[civicrm-core.git] / CRM / Core / PseudoConstant.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * Stores all constants and pseudo constants for CRM application.
15 *
16 * examples of constants are "Contact Type" which will always be either
17 * 'Individual', 'Household', 'Organization'.
18 *
19 * pseudo constants are entities from the database whose values rarely
20 * change. examples are list of countries, states, location types,
21 * relationship types.
22 *
23 * currently we're getting the data from the underlying database. this
24 * will be reworked to use caching.
25 *
26 * Note: All pseudoconstants should be uninitialized or default to NULL.
27 * This provides greater consistency/predictability after flushing.
28 *
29 * @package CRM
ca5cec67 30 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
31 */
32class CRM_Core_PseudoConstant {
33
887a4028 34 /**
d09edf64 35 * Static cache for pseudoconstant arrays.
887a4028 36 * @var array
887a4028
A
37 */
38 private static $cache;
39
6a488035
TO
40 /**
41 * activity type
42 * @var array
518fa0ee 43 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
6a488035
TO
44 */
45 private static $activityType;
46
6a488035 47 /**
100fef9d 48 * States, provinces
6a488035 49 * @var array
6a488035
TO
50 */
51 private static $stateProvince;
52
53 /**
d09edf64 54 * Counties.
6a488035 55 * @var array
6a488035
TO
56 */
57 private static $county;
58
59 /**
100fef9d 60 * States/provinces abbreviations
6a488035 61 * @var array
6a488035 62 */
be2fb01f 63 private static $stateProvinceAbbreviation = [];
6a488035
TO
64
65 /**
d09edf64 66 * Country.
6a488035 67 * @var array
6a488035
TO
68 */
69 private static $country;
70
71 /**
d09edf64 72 * CountryIsoCode.
6a488035 73 * @var array
6a488035
TO
74 */
75 private static $countryIsoCode;
76
6a488035
TO
77 /**
78 * group
79 * @var array
518fa0ee 80 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
6a488035
TO
81 */
82 private static $group;
83
6a488035 84 /**
100fef9d 85 * RelationshipType
6a488035 86 * @var array
6a488035 87 */
e51dca64 88 private static $relationshipType = [];
6a488035
TO
89
90 /**
100fef9d 91 * Civicrm groups that are not smart groups
6a488035 92 * @var array
6a488035
TO
93 */
94 private static $staticGroup;
95
6a488035 96 /**
100fef9d 97 * Currency codes
6a488035 98 * @var array
6a488035
TO
99 */
100 private static $currencyCode;
101
6a488035 102 /**
100fef9d 103 * Payment processor
6a488035 104 * @var array
6a488035
TO
105 */
106 private static $paymentProcessor;
107
108 /**
100fef9d 109 * Payment processor types
6a488035 110 * @var array
6a488035
TO
111 */
112 private static $paymentProcessorType;
113
114 /**
115 * World Region
116 * @var array
6a488035
TO
117 */
118 private static $worldRegions;
119
6a488035
TO
120 /**
121 * activity status
122 * @var array
518fa0ee 123 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
6a488035
TO
124 */
125 private static $activityStatus;
126
6a488035
TO
127 /**
128 * Visibility
129 * @var array
6a488035
TO
130 */
131 private static $visibility;
132
6a488035
TO
133 /**
134 * Greetings
135 * @var array
6a488035
TO
136 */
137 private static $greeting;
138
6a488035
TO
139 /**
140 * Extensions of type module
141 * @var array
6a488035
TO
142 */
143 private static $extensions;
144
f743a6eb
CW
145 /**
146 * Financial Account Type
147 * @var array
f743a6eb
CW
148 */
149 private static $accountOptionValues;
150
887a4028 151 /**
6d68a4cb
CW
152 * Low-level option getter, rarely accessed directly.
153 * NOTE: Rather than calling this function directly use CRM_*_BAO_*::buildOptions()
7eaff122 154 * @see https://docs.civicrm.org/dev/en/latest/framework/pseudoconstant/
6d68a4cb 155 *
76068c6a
TO
156 * NOTE: If someone undertakes a refactoring of this, please consider the use-case of
157 * the Setting.getoptions API. There is no DAO/field, but it would be nice to use the
158 * same 'pseudoconstant' struct in *.settings.php. This means loosening the coupling
159 * between $field lookup and the $pseudoconstant evaluation.
160 *
6a0b768e
TO
161 * @param string $daoName
162 * @param string $fieldName
163 * @param array $params
a42ef93c 164 * - name string name of the option group
79e6ec68 165 * - flip DEPRECATED
a42ef93c
CW
166 * - grouping boolean if true, return the value in 'grouping' column (currently unsupported for tables other than option_value)
167 * - localize boolean if true, localize the results before returning
f743a6eb 168 * - condition string|array add condition(s) to the sql query - will be concatenated using 'AND'
091fe2a8
CW
169 * - keyColumn string the column to use for 'id'
170 * - labelColumn string the column to use for 'label'
6d68a4cb 171 * - orderColumn string the column to use for sorting, defaults to 'weight' column if one exists, else defaults to labelColumn
a42ef93c
CW
172 * - onlyActive boolean return only the action option values
173 * - fresh boolean ignore cache entries and go back to DB
353ffa53 174 * @param string $context : Context string
5b22d1b8 175 * @see CRM_Core_DAO::buildOptionsContext
887a4028 176 *
8d7a9d07 177 * @return array|bool
72b3a70c 178 * array on success, FALSE on error.
a42ef93c 179 *
887a4028 180 */
be2fb01f 181 public static function get($daoName, $fieldName, $params = [], $context = NULL) {
786ad6e1 182 CRM_Core_DAO::buildOptionsContext($context);
f2b53f26 183 $flip = !empty($params['flip']);
65c86f7d 184 // Historically this was 'false' but according to the notes in
185 // CRM_Core_DAO::buildOptionsContext it should be context dependent.
186 // timidly changing for 'search' only to fix world_region in search options.
63d76404 187 $localizeDefault = in_array($context, ['search']);
786ad6e1 188 // Merge params with defaults
be2fb01f 189 $params += [
786ad6e1 190 'grouping' => FALSE,
65c86f7d 191 'localize' => $localizeDefault,
91768280 192 'onlyActive' => !($context == 'validate' || $context == 'get'),
786ad6e1 193 'fresh' => FALSE,
33e61cb8 194 'context' => $context,
a6d0f90f 195 'condition' => [],
be2fb01f 196 ];
3d182a04 197 $entity = CRM_Core_DAO_AllCoreTables::getBriefName($daoName);
f2b53f26
CW
198
199 // Custom fields are not in the schema
786ad6e1 200 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
2921fb78 201 $customField = new CRM_Core_BAO_CustomField();
a3d8b390 202 $customField->id = (int) substr($fieldName, 7);
832d5c06 203 $options = $customField->getOptions($context);
2fea9ed9
CW
204 if ($options && $flip) {
205 $options = array_flip($options);
a3d8b390 206 }
786ad6e1 207 return $options;
f2b53f26
CW
208 }
209
210 // Core field: load schema
8d7a9d07 211 $dao = new $daoName();
5fafc9b0 212 $fieldSpec = $dao->getFieldSpec($fieldName);
4268623e 213
33e61cb8 214 // Return false if field doesn't exist.
5fafc9b0 215 if (empty($fieldSpec)) {
ecc63dd6
A
216 return FALSE;
217 }
887a4028 218
0e044d89 219 // Ensure we have the canonical name for this field
220 $fieldName = $fieldSpec['name'] ?? $fieldName;
221
222 if (!empty($fieldSpec['pseudoconstant'])) {
887a4028 223 $pseudoconstant = $fieldSpec['pseudoconstant'];
cc6443c4 224
225 // if callback is specified..
22e263ad 226 if (!empty($pseudoconstant['callback'])) {
1ac9bb56 227 $fieldOptions = call_user_func(Civi\Core\Resolver::singleton()->get($pseudoconstant['callback']), $context, $params);
815facd4 228 $fieldOptions = self::formatArrayOptions($context, $fieldOptions);
ca0f1c4b
TL
229 //CRM-18223: Allow additions to field options via hook.
230 CRM_Utils_Hook::fieldOptions($entity, $fieldName, $fieldOptions, $params);
231 return $fieldOptions;
cc6443c4 232 }
233
786ad6e1 234 // Merge params with schema defaults
be2fb01f 235 $params += [
6b409353
CW
236 'keyColumn' => $pseudoconstant['keyColumn'] ?? NULL,
237 'labelColumn' => $pseudoconstant['labelColumn'] ?? NULL,
be2fb01f 238 ];
a6d0f90f
CW
239 if (!empty($pseudoconstant['condition'])) {
240 $params['condition'] = array_merge((array) $pseudoconstant['condition'], (array) $params['condition']);
241 }
091fe2a8
CW
242
243 // Fetch option group from option_value table
22e263ad 244 if (!empty($pseudoconstant['optionGroupName'])) {
786ad6e1
CW
245 if ($context == 'validate') {
246 $params['labelColumn'] = 'name';
247 }
b432ddaa
CW
248 if ($context == 'match') {
249 $params['keyColumn'] = 'name';
250 }
a42ef93c 251 // Call our generic fn for retrieving from the option_value table
33e61cb8 252 $options = CRM_Core_OptionGroup::values(
887a4028 253 $pseudoconstant['optionGroupName'],
a42ef93c
CW
254 $flip,
255 $params['grouping'],
256 $params['localize'],
f743a6eb 257 $params['condition'] ? ' AND ' . implode(' AND ', (array) $params['condition']) : NULL,
79e6ec68 258 $params['labelColumn'] ?: 'label',
a42ef93c 259 $params['onlyActive'],
c0c9cd82 260 $params['fresh'],
79e6ec68 261 $params['keyColumn'] ?: 'value',
fb011779 262 !empty($params['orderColumn']) ? $params['orderColumn'] : 'weight'
887a4028 263 );
33e61cb8
CW
264 CRM_Utils_Hook::fieldOptions($entity, $fieldName, $options, $params);
265 return $options;
887a4028 266 }
091fe2a8
CW
267
268 // Fetch options from other tables
887a4028 269 if (!empty($pseudoconstant['table'])) {
a42ef93c 270 CRM_Utils_Array::remove($params, 'flip', 'fresh');
b53c3468 271 // Normalize params so the serialized cache string will be consistent.
887a4028 272 ksort($params);
a1ef51e2 273 $cacheKey = $daoName . $fieldName . serialize($params);
a1ef51e2 274 // Retrieve cached options
14b9e069 275 if (isset(\Civi::$statics[__CLASS__][$cacheKey]) && empty($params['fresh'])) {
276 $output = \Civi::$statics[__CLASS__][$cacheKey];
887a4028 277 }
a1ef51e2 278 else {
b53c3468 279 $output = self::renderOptionsFromTablePseudoconstant($pseudoconstant, $params, ($fieldSpec['localize_context'] ?? NULL), $context);
33e61cb8 280 CRM_Utils_Hook::fieldOptions($entity, $fieldName, $output, $params);
14b9e069 281 \Civi::$statics[__CLASS__][$cacheKey] = $output;
a1ef51e2
CW
282 }
283 return $flip ? array_flip($output) : $output;
887a4028
A
284 }
285 }
a3d8b390
CW
286
287 // Return "Yes" and "No" for boolean fields
288 elseif (CRM_Utils_Array::value('type', $fieldSpec) === CRM_Utils_Type::T_BOOLEAN) {
be2fb01f 289 $output = $context == 'validate' ? [0, 1] : CRM_Core_SelectValues::boolean();
33e61cb8 290 CRM_Utils_Hook::fieldOptions($entity, $fieldName, $output, $params);
a3d8b390
CW
291 return $flip ? array_flip($output) : $output;
292 }
887a4028
A
293 // If we're still here, it's an error. Return FALSE.
294 return FALSE;
295 }
296
6a488035 297 /**
d09edf64 298 * Fetch the translated label for a field given its key.
dcda1cd5 299 *
6a0b768e
TO
300 * @param string $baoName
301 * @param string $fieldName
e97c66ff 302 * @param string|int $key
a8c23526
CW
303 *
304 * TODO: Accept multivalued input?
dcda1cd5 305 *
2a3f958d
CW
306 * @return bool|null|string
307 * FALSE if the given field has no associated option list
308 * NULL if the given key has no corresponding option
309 * String if label is found
dcda1cd5 310 */
00be9182 311 public static function getLabel($baoName, $fieldName, $key) {
a8c23526
CW
312 $values = $baoName::buildOptions($fieldName, 'get');
313 if ($values === FALSE) {
314 return FALSE;
315 }
914d3734 316 return $values[$key] ?? NULL;
a8c23526
CW
317 }
318
319 /**
d09edf64 320 * Fetch the machine name for a field given its key.
a8c23526 321 *
6a0b768e
TO
322 * @param string $baoName
323 * @param string $fieldName
e97c66ff 324 * @param string|int $key
a8c23526
CW
325 *
326 * @return bool|null|string
327 * FALSE if the given field has no associated option list
328 * NULL if the given key has no corresponding option
329 * String if label is found
330 */
00be9182 331 public static function getName($baoName, $fieldName, $key) {
a8c23526 332 $values = $baoName::buildOptions($fieldName, 'validate');
2a3f958d
CW
333 if ($values === FALSE) {
334 return FALSE;
335 }
914d3734 336 return $values[$key] ?? NULL;
2a3f958d 337 }
dcda1cd5
CW
338
339 /**
d09edf64 340 * Fetch the key for a field option given its name.
dcda1cd5 341 *
6a0b768e
TO
342 * @param string $baoName
343 * @param string $fieldName
e97c66ff 344 * @param string|int $value
dcda1cd5 345 *
8d7a9d07 346 * @return bool|null|string|int
2a3f958d
CW
347 * FALSE if the given field has no associated option list
348 * NULL if the given key has no corresponding option
349 * String|Number if key is found
dcda1cd5 350 */
00be9182 351 public static function getKey($baoName, $fieldName, $value) {
a8c23526 352 $values = $baoName::buildOptions($fieldName, 'validate');
2a3f958d
CW
353 if ($values === FALSE) {
354 return FALSE;
355 }
356 return CRM_Utils_Array::key($value, $values);
357 }
dcda1cd5 358
e869b07d
CW
359 /**
360 * Lookup the admin page at which a field's option list can be edited
361 * @param $fieldSpec
362 * @return string|null
363 */
00be9182 364 public static function getOptionEditUrl($fieldSpec) {
e869b07d
CW
365 // If it's an option group, that's easy
366 if (!empty($fieldSpec['pseudoconstant']['optionGroupName'])) {
367 return 'civicrm/admin/options/' . $fieldSpec['pseudoconstant']['optionGroupName'];
368 }
369 // For everything else...
370 elseif (!empty($fieldSpec['pseudoconstant']['table'])) {
371 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($fieldSpec['pseudoconstant']['table']);
372 if (!$daoName) {
373 return NULL;
374 }
375 // We don't have good mapping so have to do a bit of guesswork from the menu
e1462487 376 list(, $parent, , $child) = explode('_', $daoName);
e869b07d 377 $sql = "SELECT path FROM civicrm_menu
e1462487
CW
378 WHERE page_callback LIKE '%CRM_Admin_Page_$child%' OR page_callback LIKE '%CRM_{$parent}_Page_$child%'
379 ORDER BY page_callback
e869b07d 380 LIMIT 1";
46710ea6 381 return CRM_Core_DAO::singleValueQuery($sql);
e869b07d
CW
382 }
383 return NULL;
384 }
385
dcda1cd5 386 /**
887688b9 387 * @deprecated generic populate method.
c490a46a 388 * All pseudoconstant functions that use this method are also @deprecated
6a488035
TO
389 *
390 * The static array $var is populated from the db
391 * using the <b>$name DAO</b>.
392 *
393 * Note: any database errors will be trapped by the DAO.
394 *
6a0b768e
TO
395 * @param array $var
396 * The associative array we will fill.
397 * @param string $name
398 * The name of the DAO.
399 * @param bool $all
400 * Get all objects. default is to get only active ones.
401 * @param string $retrieve
402 * The field that we are interested in (normally name, differs in some objects).
403 * @param string $filter
404 * The field that we want to filter the result set with.
405 * @param string $condition
406 * The condition that gets passed to the final query as the WHERE clause.
745b795a 407 *
8eedd10a 408 * @param bool $orderby
745b795a 409 * @param string $key
8eedd10a 410 * @param bool $force
6a488035 411 *
8eedd10a 412 * @return array
6a488035 413 */
8360b701
DL
414 public static function populate(
415 &$var,
416 $name,
417 $all = FALSE,
418 $retrieve = 'name',
419 $filter = 'is_active',
420 $condition = NULL,
421 $orderby = NULL,
422 $key = 'id',
423 $force = NULL
424 ) {
77f080cb 425 $cacheKey = CRM_Utils_Cache::cleanKey("CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}");
353ffa53
TO
426 $cache = CRM_Utils_Cache::singleton();
427 $var = $cache->get($cacheKey);
4f468a50 428 if ($var !== NULL && empty($force)) {
6a488035
TO
429 return $var;
430 }
431
5836c35a 432 /* @var CRM_Core_DAO $object */
8d7a9d07 433 $object = new $name();
6a488035
TO
434
435 $object->selectAdd();
436 $object->selectAdd("$key, $retrieve");
437 if ($condition) {
438 $object->whereAdd($condition);
439 }
440
441 if (!$orderby) {
442 $object->orderBy($retrieve);
443 }
444 else {
445 $object->orderBy($orderby);
446 }
447
448 if (!$all) {
449 $object->$filter = 1;
5836c35a
CW
450 $aclClauses = array_filter($name::getSelectWhereClause());
451 foreach ($aclClauses as $clause) {
452 $object->whereAdd($clause);
453 }
6a488035
TO
454 }
455
456 $object->find();
be2fb01f 457 $var = [];
6a488035
TO
458 while ($object->fetch()) {
459 $var[$object->$key] = $object->$retrieve;
460 }
461
462 $cache->set($cacheKey, $var);
463 }
464
465 /**
d09edf64 466 * Flush given pseudoconstant so it can be reread from db.
6a488035
TO
467 * nex time it's requested.
468 *
2a6da8d7 469 * @param bool|string $name pseudoconstant to be flushed
6a488035 470 */
2683ce94 471 public static function flush($name = 'cache') {
80085473 472 if (isset(self::$$name)) {
fa56270d
CW
473 self::$$name = NULL;
474 }
80085473
CW
475 if ($name == 'cache') {
476 CRM_Core_OptionGroup::flushAll();
7c990617 477 if (isset(\Civi::$statics[__CLASS__])) {
478 unset(\Civi::$statics[__CLASS__]);
479 }
80085473 480 }
6a488035
TO
481 }
482
6a488035 483 /**
c490a46a 484 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
a19392e7 485 *
6a488035
TO
486 * Get all Activty types.
487 *
488 * The static array activityType is returned
489 *
6a488035 490 *
a6c01b45
CW
491 * @return array
492 * array reference of all activity types.
6a488035
TO
493 */
494 public static function &activityType() {
495 $args = func_get_args();
496 $all = CRM_Utils_Array::value(0, $args, TRUE);
497 $includeCaseActivities = CRM_Utils_Array::value(1, $args, FALSE);
498 $reset = CRM_Utils_Array::value(2, $args, FALSE);
499 $returnColumn = CRM_Utils_Array::value(3, $args, 'label');
500 $includeCampaignActivities = CRM_Utils_Array::value(4, $args, FALSE);
501 $onlyComponentActivities = CRM_Utils_Array::value(5, $args, FALSE);
502 $index = (int) $all . '_' . $returnColumn . '_' . (int) $includeCaseActivities;
503 $index .= '_' . (int) $includeCampaignActivities;
504 $index .= '_' . (int) $onlyComponentActivities;
505
506 if (NULL === self::$activityType) {
be2fb01f 507 self::$activityType = [];
6a488035
TO
508 }
509
510 if (!isset(self::$activityType[$index]) || $reset) {
511 $condition = NULL;
512 if (!$all) {
513 $condition = 'AND filter = 0';
514 }
515 $componentClause = " v.component_id IS NULL";
516 if ($onlyComponentActivities) {
517 $componentClause = " v.component_id IS NOT NULL";
518 }
519
be2fb01f 520 $componentIds = [];
6a488035
TO
521 $compInfo = CRM_Core_Component::getEnabledComponents();
522
523 // build filter for listing activity types only if their
524 // respective components are enabled
525 foreach ($compInfo as $compName => $compObj) {
526 if ($compName == 'CiviCase') {
527 if ($includeCaseActivities) {
528 $componentIds[] = $compObj->componentID;
529 }
530 }
531 elseif ($compName == 'CiviCampaign') {
532 if ($includeCampaignActivities) {
533 $componentIds[] = $compObj->componentID;
534 }
535 }
536 else {
537 $componentIds[] = $compObj->componentID;
538 }
539 }
540
541 if (count($componentIds)) {
542 $componentIds = implode(',', $componentIds);
543 $componentClause = " ($componentClause OR v.component_id IN ($componentIds))";
544 if ($onlyComponentActivities) {
545 $componentClause = " ( v.component_id IN ($componentIds ) )";
546 }
547 }
bdd7b275 548 $condition = $condition . ' AND ' . $componentClause;
6a488035
TO
549
550 self::$activityType[$index] = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
551 }
552 return self::$activityType[$index];
553 }
0e6e8724 554
6a488035
TO
555 /**
556 * Get all the State/Province from database.
557 *
558 * The static array stateProvince is returned, and if it's
559 * called the first time, the <b>State Province DAO</b> is used
560 * to get all the States.
561 *
562 * Note: any database errors will be trapped by the DAO.
563 *
6a488035 564 *
6a0b768e 565 * @param bool|int $id - Optional id to return
6a488035 566 *
2a6da8d7 567 * @param bool $limit
6a488035 568 *
a6c01b45
CW
569 * @return array
570 * array reference of all State/Provinces.
6a488035
TO
571 */
572 public static function &stateProvince($id = FALSE, $limit = TRUE) {
f3acfdd9 573 if (($id && empty(self::$stateProvince[$id])) || !self::$stateProvince || !$id) {
6a488035 574 $whereClause = FALSE;
6a488035
TO
575 if ($limit) {
576 $countryIsoCodes = self::countryIsoCode();
0acb7f15 577 $limitCodes = CRM_Core_BAO_Country::provinceLimit();
be2fb01f 578 $limitIds = [];
6a488035
TO
579 foreach ($limitCodes as $code) {
580 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
581 }
582 if (!empty($limitIds)) {
583 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
584 }
585 else {
586 $whereClause = FALSE;
587 }
588 }
589 self::populate(self::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
590
591 // localise the province names if in an non-en_US locale
98466ff9 592 $tsLocale = CRM_Core_I18n::getLocale();
6a488035
TO
593 if ($tsLocale != '' and $tsLocale != 'en_US') {
594 $i18n = CRM_Core_I18n::singleton();
be2fb01f 595 $i18n->localizeArray(self::$stateProvince, [
353ffa53 596 'context' => 'province',
be2fb01f 597 ]);
6a488035
TO
598 self::$stateProvince = CRM_Utils_Array::asort(self::$stateProvince);
599 }
600 }
601 if ($id) {
602 if (array_key_exists($id, self::$stateProvince)) {
603 return self::$stateProvince[$id];
604 }
605 else {
606 $result = NULL;
607 return $result;
608 }
609 }
610 return self::$stateProvince;
611 }
612
613 /**
614 * Get all the State/Province abbreviations from the database.
615 *
616 * Same as above, except gets the abbreviations instead of the names.
617 *
6a488035 618 *
6a0b768e 619 * @param bool|int $id - Optional id to return
2a6da8d7
EM
620 *
621 * @param bool $limit
6a488035 622 *
a6c01b45
CW
623 * @return array
624 * array reference of all State/Province abbreviations.
6a488035 625 */
a8215a8d 626 public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
05a8d245 627 if ($id && is_numeric($id)) {
628 if (!array_key_exists($id, (array) self::$stateProvinceAbbreviation)) {
629 $query = "SELECT abbreviation
6a488035
TO
630FROM civicrm_state_province
631WHERE id = %1";
be2fb01f
CW
632 $params = [
633 1 => [
05a8d245 634 $id,
635 'Integer',
be2fb01f
CW
636 ],
637 ];
05a8d245 638 self::$stateProvinceAbbreviation[$id] = CRM_Core_DAO::singleValueQuery($query, $params);
639 }
640 return self::$stateProvinceAbbreviation[$id];
6a488035 641 }
05a8d245 642 else {
6a488035
TO
643 $whereClause = FALSE;
644
645 if ($limit) {
6a488035 646 $countryIsoCodes = self::countryIsoCode();
0acb7f15 647 $limitCodes = CRM_Core_BAO_Country::provinceLimit();
be2fb01f 648 $limitIds = [];
6a488035
TO
649 foreach ($limitCodes as $code) {
650 $tmpArray = array_keys($countryIsoCodes, $code);
651
652 if (!empty($tmpArray)) {
653 $limitIds[] = array_shift($tmpArray);
654 }
655 }
656 if (!empty($limitIds)) {
657 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
658 }
659 }
660 self::populate(self::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
661 }
662
6a488035
TO
663 return self::$stateProvinceAbbreviation;
664 }
665
4352bd72 666 /**
667 * Get all the State/Province abbreviations from the database for the specified country.
668 *
669 * @param int $countryID
670 *
671 * @return array
672 * array of all State/Province abbreviations for the given country.
673 */
674 public static function stateProvinceAbbreviationForCountry($countryID) {
675 if (!isset(\Civi::$statics[__CLASS__]['stateProvinceAbbreviationForCountry'][$countryID])) {
be2fb01f 676 \Civi::$statics[__CLASS__]['stateProvinceAbbreviationForCountry'][$countryID] = [];
4352bd72 677 }
678 self::populate(\Civi::$statics[__CLASS__]['stateProvinceAbbreviationForCountry'][$countryID], 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', "country_id = " . (int) $countryID, 'abbreviation');
679 return \Civi::$statics[__CLASS__]['stateProvinceAbbreviationForCountry'][$countryID];
680 }
681
682 /**
683 * Get all the State/Province abbreviations from the database for the default country.
684 *
685 * @return array
686 * array of all State/Province abbreviations for the given country.
687 */
688 public static function stateProvinceAbbreviationForDefaultCountry() {
689 return CRM_Core_PseudoConstant::stateProvinceAbbreviationForCountry(Civi::settings()->get('defaultContactCountry'));
690 }
691
6a488035
TO
692 /**
693 * Get all the countries from database.
694 *
695 * The static array country is returned, and if it's
696 * called the first time, the <b>Country DAO</b> is used
697 * to get all the countries.
698 *
699 * Note: any database errors will be trapped by the DAO.
700 *
6a488035 701 *
dd244018 702 * @param bool|int $id - Optional id to return
6a488035 703 *
dd244018 704 * @param bool $applyLimit
6a488035 705 *
1273d77c 706 * @return array|null
a6c01b45 707 * array reference of all countries.
6a488035
TO
708 */
709 public static function country($id = FALSE, $applyLimit = TRUE) {
f3acfdd9 710 if (($id && empty(self::$country[$id])) || !self::$country || !$id) {
6a488035
TO
711
712 $config = CRM_Core_Config::singleton();
be2fb01f 713 $limitCodes = [];
6a488035
TO
714
715 if ($applyLimit) {
716 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
717 // (ensuring it's a subset of the legal values)
718 // K/P: We need to fix this, i dont think it works with new setting files
0acb7f15 719 $limitCodes = CRM_Core_BAO_Country::countryLimit();
6a488035 720 if (!is_array($limitCodes)) {
be2fb01f 721 $limitCodes = [
6a488035 722 $config->countryLimit => 1,
be2fb01f 723 ];
6a488035
TO
724 }
725
726 $limitCodes = array_intersect(self::countryIsoCode(), $limitCodes);
727 }
728
729 if (count($limitCodes)) {
730 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
731 }
732 else {
733 $whereClause = NULL;
734 }
735
736 self::populate(self::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
737
3c4a4657 738 self::$country = CRM_Core_BAO_Country::_defaultContactCountries(self::$country);
6a488035
TO
739 }
740 if ($id) {
741 if (array_key_exists($id, self::$country)) {
742 return self::$country[$id];
743 }
744 else {
1273d77c 745 return NULL;
6a488035
TO
746 }
747 }
748 return self::$country;
749 }
750
751 /**
752 * Get all the country ISO Code abbreviations from the database.
753 *
754 * The static array countryIsoCode is returned, and if it's
755 * called the first time, the <b>Country DAO</b> is used
756 * to get all the countries' ISO codes.
757 *
758 * Note: any database errors will be trapped by the DAO.
759 *
6a488035 760 *
fd31fa4c 761 * @param bool $id
6a488035 762 *
a6c01b45
CW
763 * @return array
764 * array reference of all country ISO codes.
6a488035
TO
765 */
766 public static function &countryIsoCode($id = FALSE) {
767 if (!self::$countryIsoCode) {
768 self::populate(self::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
769 }
770 if ($id) {
771 if (array_key_exists($id, self::$countryIsoCode)) {
772 return self::$countryIsoCode[$id];
773 }
774 else {
7cdc9e9f 775 return CRM_Core_DAO::$_nullObject;
6a488035
TO
776 }
777 }
778 return self::$countryIsoCode;
779 }
780
6a488035 781 /**
c490a46a 782 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
29494eef 783 *
6a488035
TO
784 * Get all groups from database
785 *
786 * The static array group is returned, and if it's
787 * called the first time, the <b>Group DAO</b> is used
788 * to get all the groups.
789 *
790 * Note: any database errors will be trapped by the DAO.
791 *
6a0b768e
TO
792 * @param string $groupType
793 * Type of group(Access/Mailing).
794 * @param bool $excludeHidden
795 * Exclude hidden groups.
6a488035 796 *
6a488035 797 *
a6c01b45
CW
798 * @return array
799 * array reference of all groups.
6a488035 800 */
addbec40 801 public static function allGroup($groupType = NULL, $excludeHidden = TRUE) {
1678a63b 802 if ($groupType === 'validate') {
803 // validate gets passed through from getoptions. Handle in the deprecated
804 // fn rather than change the new pattern.
805 $groupType = NULL;
806 }
6a488035 807 $condition = CRM_Contact_BAO_Group::groupTypeCondition($groupType, $excludeHidden);
addbec40 808 $groupKey = ($groupType ? $groupType : 'null') . !empty($excludeHidden);
6a488035 809
6d054a8e 810 if (!isset(Civi::$statics[__CLASS__]['groups']['allGroup'][$groupKey])) {
811 self::populate(Civi::$statics[__CLASS__]['groups']['allGroup'][$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
6a488035 812 }
6d054a8e 813 return Civi::$statics[__CLASS__]['groups']['allGroup'][$groupKey];
6a488035
TO
814 }
815
6a488035 816 /**
d09edf64 817 * Get all permissioned groups from database.
6a488035
TO
818 *
819 * The static array group is returned, and if it's
820 * called the first time, the <b>Group DAO</b> is used
821 * to get all the groups.
822 *
823 * Note: any database errors will be trapped by the DAO.
824 *
6a0b768e
TO
825 * @param string $groupType
826 * Type of group(Access/Mailing).
827 * @param bool $excludeHidden
828 * Exclude hidden groups.
dd244018 829 *
6a488035 830 *
a6c01b45
CW
831 * @return array
832 * array reference of all groups.
6a488035
TO
833 */
834 public static function group($groupType = NULL, $excludeHidden = TRUE) {
835 return CRM_Core_Permission::group($groupType, $excludeHidden);
836 }
837
24431f7b 838 /**
d09edf64 839 * Fetch groups in a nested format suitable for use in select form element.
24431f7b
CW
840 * @param bool $checkPermissions
841 * @param string|null $groupType
842 * @param bool $excludeHidden
843 * @return array
844 */
c6fe32d7 845 public static function nestedGroup(bool $checkPermissions = TRUE, $groupType = NULL, bool $excludeHidden = TRUE) {
24431f7b
CW
846 $groups = $checkPermissions ? self::group($groupType, $excludeHidden) : self::allGroup($groupType, $excludeHidden);
847 return CRM_Contact_BAO_Group::getGroupsHierarchy($groups, NULL, '&nbsp;&nbsp;', TRUE);
848 }
849
6a488035 850 /**
d09edf64 851 * Get all permissioned groups from database.
6a488035
TO
852 *
853 * The static array group is returned, and if it's
854 * called the first time, the <b>Group DAO</b> is used
855 * to get all the groups.
856 *
857 * Note: any database errors will be trapped by the DAO.
858 *
6a488035 859 *
dd244018
EM
860 * @param bool $onlyPublic
861 * @param null $groupType
862 * @param bool $excludeHidden
6a488035 863 *
a6c01b45
CW
864 * @return array
865 * array reference of all groups.
6a488035
TO
866 */
867 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
868 if (!self::$staticGroup) {
869 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
870 if ($onlyPublic) {
871 $condition .= " AND visibility != 'User and User Admin Only'";
872 }
873
874 if ($groupType) {
875 $condition .= ' AND ' . CRM_Contact_BAO_Group::groupTypeCondition($groupType);
876 }
877
878 if ($excludeHidden) {
879 $condition .= ' AND is_hidden != 1 ';
880 }
881
882 self::populate(self::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
883 }
884
885 return self::$staticGroup;
886 }
887
6a488035
TO
888 /**
889 * Get all Relationship Types from database.
890 *
891 * The static array group is returned, and if it's
892 * called the first time, the <b>RelationshipType DAO</b> is used
893 * to get all the relationship types.
894 *
895 * Note: any database errors will be trapped by the DAO.
896 *
6a0b768e
TO
897 * @param string $valueColumnName
898 * Db column name/label.
899 * @param bool $reset
900 * Reset relationship types if true.
bf48aa29 901 * @param bool $isActive
fa8e67b8 902 * Filter by is_active. NULL to disable.
6a488035 903 *
a6c01b45
CW
904 * @return array
905 * array reference of all relationship types.
6a488035 906 */
e51dca64 907 public static function relationshipType($valueColumnName = 'label', $reset = FALSE, $isActive = 1) {
fa8e67b8 908 $cacheKey = $valueColumnName . '::' . $isActive;
e51dca64 909 if (!isset(self::$relationshipType[$cacheKey]) || $reset) {
be2fb01f 910 self::$relationshipType[$cacheKey] = [];
6a488035
TO
911
912 //now we have name/label columns CRM-3336
913 $column_a_b = "{$valueColumnName}_a_b";
914 $column_b_a = "{$valueColumnName}_b_a";
915
916 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
917 $relationshipTypeDAO->selectAdd();
918 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
fa8e67b8
TO
919 if ($isActive !== NULL) {
920 $relationshipTypeDAO->is_active = $isActive;
921 }
6a488035
TO
922 $relationshipTypeDAO->find();
923 while ($relationshipTypeDAO->fetch()) {
924
be2fb01f 925 self::$relationshipType[$cacheKey][$relationshipTypeDAO->id] = [
05802b8e 926 'id' => $relationshipTypeDAO->id,
6a488035
TO
927 $column_a_b => $relationshipTypeDAO->$column_a_b,
928 $column_b_a => $relationshipTypeDAO->$column_b_a,
929 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
930 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
931 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
932 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
be2fb01f 933 ];
6a488035
TO
934 }
935 }
936
fa8e67b8 937 return self::$relationshipType[$cacheKey];
6a488035
TO
938 }
939
bf01b886
CW
940 /**
941 * Name => Label pairs for all relationship types
942 *
943 * @return array
944 */
945 public static function relationshipTypeOptions() {
946 $relationshipTypes = [];
947 $relationshipLabels = self::relationshipType();
948 foreach (self::relationshipType('name') as $id => $type) {
949 $relationshipTypes[$type['name_a_b']] = $relationshipLabels[$id]['label_a_b'];
950 if ($type['name_b_a'] && $type['name_b_a'] != $type['name_a_b']) {
951 $relationshipTypes[$type['name_b_a']] = $relationshipLabels[$id]['label_b_a'];
952 }
953 }
954 return $relationshipTypes;
955 }
956
6a488035 957 /**
100fef9d 958 * Get all the ISO 4217 currency codes
6a488035
TO
959 *
960 * so far, we use this for validation only, so there's no point of putting this into the database
961 *
6a488035 962 *
a6c01b45
CW
963 * @return array
964 * array reference of all currency codes
6a488035
TO
965 */
966 public static function &currencyCode() {
967 if (!self::$currencyCode) {
3b5223ee
HF
968
969 $query = "SELECT name FROM civicrm_currency";
970 $dao = CRM_Core_DAO::executeQuery($query);
be2fb01f 971 $currencyCode = [];
3b5223ee
HF
972 while ($dao->fetch()) {
973 self::$currencyCode[] = $dao->name;
974 }
6a488035
TO
975 }
976 return self::$currencyCode;
977 }
978
979 /**
980 * Get all the County from database.
981 *
982 * The static array county is returned, and if it's
983 * called the first time, the <b>County DAO</b> is used
984 * to get all the Counties.
985 *
986 * Note: any database errors will be trapped by the DAO.
987 *
6a488035 988 *
6a0b768e 989 * @param bool|int $id - Optional id to return
6a488035 990 *
a6c01b45
CW
991 * @return array
992 * array reference of all Counties
6a488035
TO
993 */
994 public static function &county($id = FALSE) {
995 if (!self::$county) {
996
997 $config = CRM_Core_Config::singleton();
998 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
999 self::populate(self::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1000 }
1001 if ($id) {
1002 if (array_key_exists($id, self::$county)) {
1003 return self::$county[$id];
1004 }
1005 else {
7cdc9e9f 1006 return CRM_Core_DAO::$_nullObject;
6a488035
TO
1007 }
1008 }
1009 return self::$county;
1010 }
1011
6a488035 1012 /**
c490a46a 1013 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
6a488035
TO
1014 * Get all active payment processors
1015 *
1016 * The static array paymentProcessor is returned
1017 *
6a488035 1018 *
6a0b768e
TO
1019 * @param bool $all
1020 * Get payment processors - default is to get only active ones.
1021 * @param bool $test
1022 * Get test payment processors.
6a488035 1023 *
77b97be7 1024 * @param null $additionalCond
6a488035 1025 *
a6c01b45
CW
1026 * @return array
1027 * array of all payment processors
6a488035 1028 */
d6944518 1029 public static function paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
6a488035
TO
1030 $condition = "is_test = ";
1031 $condition .= ($test) ? '1' : '0';
1032
1033 if ($additionalCond) {
1034 $condition .= " AND ( $additionalCond ) ";
1035 }
1036
b44e3f84 1037 // CRM-7178. Make sure we only include payment processors valid in this
6a488035
TO
1038 // domain
1039 $condition .= " AND domain_id = " . CRM_Core_Config::domainID();
1040
1041 $cacheKey = $condition . '_' . (int) $all;
1042 if (!isset(self::$paymentProcessor[$cacheKey])) {
1043 self::populate(self::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1044 }
1045
1046 return self::$paymentProcessor[$cacheKey];
1047 }
1048
1049 /**
c490a46a 1050 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
6a488035
TO
1051 *
1052 * The static array paymentProcessorType is returned
1053 *
6a488035 1054 *
6a0b768e
TO
1055 * @param bool $all
1056 * Get payment processors - default is to get only active ones.
6a488035 1057 *
100fef9d 1058 * @param int $id
77b97be7 1059 * @param string $return
6a488035 1060 *
a6c01b45
CW
1061 * @return array
1062 * array of all payment processor types
6a488035
TO
1063 */
1064 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
86bfa4f6 1065 $cacheKey = $id . '_' . $return;
6a488035
TO
1066 if (empty(self::$paymentProcessorType[$cacheKey])) {
1067 self::populate(self::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1068 }
f3acfdd9 1069 if ($id && !empty(self::$paymentProcessorType[$cacheKey][$id])) {
6a488035
TO
1070 return self::$paymentProcessorType[$cacheKey][$id];
1071 }
1072 return self::$paymentProcessorType[$cacheKey];
1073 }
1074
1075 /**
d09edf64 1076 * Get all the World Regions from Database.
6a488035 1077 *
6a488035 1078 *
77b97be7
EM
1079 * @param bool $id
1080 *
a6c01b45
CW
1081 * @return array
1082 * array reference of all World Regions
6a488035
TO
1083 */
1084 public static function &worldRegion($id = FALSE) {
1085 if (!self::$worldRegions) {
1086 self::populate(self::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1087 }
1088
1089 if ($id) {
1090 if (array_key_exists($id, self::$worldRegions)) {
1091 return self::$worldRegions[$id];
1092 }
1093 else {
7cdc9e9f 1094 return CRM_Core_DAO::$_nullObject;
6a488035
TO
1095 }
1096 }
1097
1098 return self::$worldRegions;
1099 }
1100
6a488035 1101 /**
c490a46a 1102 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
29494eef 1103 *
6a488035
TO
1104 * Get all Activity Statuses.
1105 *
1106 * The static array activityStatus is returned
1107 *
6a488035 1108 *
77b97be7
EM
1109 * @param string $column
1110 *
a6c01b45
CW
1111 * @return array
1112 * array reference of all activity statuses
6a488035
TO
1113 */
1114 public static function &activityStatus($column = 'label') {
1115 if (NULL === self::$activityStatus) {
be2fb01f 1116 self::$activityStatus = [];
6a488035
TO
1117 }
1118 if (!array_key_exists($column, self::$activityStatus)) {
be2fb01f 1119 self::$activityStatus[$column] = [];
6a488035
TO
1120
1121 self::$activityStatus[$column] = CRM_Core_OptionGroup::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1122 }
1123
1124 return self::$activityStatus[$column];
1125 }
1126
6a488035 1127 /**
c490a46a 1128 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
a19392e7 1129 *
6a488035
TO
1130 * Get all Visibility levels.
1131 *
1132 * The static array visibility is returned
1133 *
6a488035 1134 *
77b97be7 1135 * @param string $column
6a488035 1136 *
a6c01b45
CW
1137 * @return array
1138 * array reference of all Visibility levels.
6a488035
TO
1139 */
1140 public static function &visibility($column = 'label') {
1141 if (!isset(self::$visibility)) {
be2fb01f 1142 self::$visibility = [];
6a488035
TO
1143 }
1144
1145 if (!isset(self::$visibility[$column])) {
1146 self::$visibility[$column] = CRM_Core_OptionGroup::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
2aa397bc 1147 }
6a488035
TO
1148
1149 return self::$visibility[$column];
1150 }
1151
a0ee3941 1152 /**
100fef9d 1153 * @param int $countryID
a0ee3941
EM
1154 * @param string $field
1155 *
1156 * @return array
1157 */
6a488035
TO
1158 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1159 static $_cache = NULL;
1160
1161 $cacheKey = "{$countryID}_{$field}";
1162 if (!$_cache) {
be2fb01f 1163 $_cache = [];
6a488035
TO
1164 }
1165
1166 if (!empty($_cache[$cacheKey])) {
1167 return $_cache[$cacheKey];
1168 }
1169
1170 $query = "
1171SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1172 FROM civicrm_state_province
1173WHERE country_id = %1
1174ORDER BY name";
be2fb01f
CW
1175 $params = [
1176 1 => [
6a488035
TO
1177 $countryID,
1178 'Integer',
be2fb01f
CW
1179 ],
1180 ];
6a488035
TO
1181
1182 $dao = CRM_Core_DAO::executeQuery($query, $params);
1183
be2fb01f 1184 $result = [];
6a488035
TO
1185 while ($dao->fetch()) {
1186 $result[$dao->id] = $dao->name;
1187 }
1188
1189 // localise the stateProvince names if in an non-en_US locale
1190 $config = CRM_Core_Config::singleton();
98466ff9 1191 $tsLocale = CRM_Core_I18n::getLocale();
6a488035
TO
1192 if ($tsLocale != '' and $tsLocale != 'en_US') {
1193 $i18n = CRM_Core_I18n::singleton();
be2fb01f 1194 $i18n->localizeArray($result, [
6a488035 1195 'context' => 'province',
be2fb01f 1196 ]);
6a488035
TO
1197 $result = CRM_Utils_Array::asort($result);
1198 }
1199
1200 $_cache[$cacheKey] = $result;
1201
1202 CRM_Utils_Hook::buildStateProvinceForCountry($countryID, $result);
1203
1204 return $result;
1205 }
1206
a0ee3941 1207 /**
100fef9d 1208 * @param int $stateID
a0ee3941
EM
1209 *
1210 * @return array
1211 */
6a488035
TO
1212 public static function &countyForState($stateID) {
1213 if (is_array($stateID)) {
1214 $states = implode(", ", $stateID);
1215 $query = "
1216 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1217 FROM civicrm_county
1218 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1219 WHERE civicrm_county.state_province_id in ( $states )
1220 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1221
1222 $dao = CRM_Core_DAO::executeQuery($query);
1223
be2fb01f 1224 $result = [];
6a488035
TO
1225 while ($dao->fetch()) {
1226 $result[$dao->id] = $dao->abbreviation . ': ' . $dao->name;
1227 }
1228 }
1229 else {
1230
1231 static $_cache = NULL;
1232
1233 $cacheKey = "{$stateID}_name";
1234 if (!$_cache) {
be2fb01f 1235 $_cache = [];
6a488035
TO
1236 }
1237
1238 if (!empty($_cache[$cacheKey])) {
1239 return $_cache[$cacheKey];
1240 }
1241
1242 $query = "
1243 SELECT civicrm_county.name name, civicrm_county.id id
1244 FROM civicrm_county
1245 WHERE state_province_id = %1
1246 ORDER BY name";
be2fb01f
CW
1247 $params = [
1248 1 => [
6a488035
TO
1249 $stateID,
1250 'Integer',
be2fb01f
CW
1251 ],
1252 ];
6a488035
TO
1253
1254 $dao = CRM_Core_DAO::executeQuery($query, $params);
1255
be2fb01f 1256 $result = [];
6a488035
TO
1257 while ($dao->fetch()) {
1258 $result[$dao->id] = $dao->name;
1259 }
1260 }
1261
1262 return $result;
1263 }
1264
b05e28de
DL
1265 /**
1266 * Given a state ID return the country ID, this allows
1267 * us to populate forms and values for downstream code
1268 *
5a4f6742 1269 * @param int $stateID
b05e28de 1270 *
1273d77c 1271 * @return int|null
a6c01b45 1272 * the country id that the state belongs to
b05e28de 1273 */
00be9182 1274 public static function countryIDForStateID($stateID) {
b05e28de 1275 if (empty($stateID)) {
1273d77c 1276 return NULL;
b05e28de
DL
1277 }
1278
1279 $query = "
1280SELECT country_id
1281FROM civicrm_state_province
1282WHERE id = %1
1283";
be2fb01f 1284 $params = [1 => [$stateID, 'Integer']];
b05e28de
DL
1285
1286 return CRM_Core_DAO::singleValueQuery($query, $params);
1287 }
1288
6a488035
TO
1289 /**
1290 * Get all types of Greetings.
1291 *
1292 * The static array of greeting is returned
1293 *
6a488035 1294 *
6a0b768e
TO
1295 * @param $filter
1296 * Get All Email Greetings - default is to get only active ones.
6a488035 1297 *
77b97be7 1298 * @param string $columnName
6a488035 1299 *
a6c01b45
CW
1300 * @return array
1301 * array reference of all greetings.
6a488035
TO
1302 */
1303 public static function greeting($filter, $columnName = 'label') {
5f35a2d9 1304 if (!isset(Civi::$statics[__CLASS__]['greeting'])) {
be2fb01f 1305 Civi::$statics[__CLASS__]['greeting'] = [];
5f35a2d9 1306 }
1307
6a488035
TO
1308 $index = $filter['greeting_type'] . '_' . $columnName;
1309
1310 // also add contactType to the array
9c1bc317 1311 $contactType = $filter['contact_type'] ?? NULL;
6a488035
TO
1312 if ($contactType) {
1313 $index .= '_' . $contactType;
1314 }
1315
f3acfdd9 1316 if (empty(Civi::$statics[__CLASS__]['greeting'][$index])) {
6a488035
TO
1317 $filterCondition = NULL;
1318 if ($contactType) {
1319 $filterVal = 'v.filter =';
1320 switch ($contactType) {
1321 case 'Individual':
1322 $filterVal .= "1";
1323 break;
1324
1325 case 'Household':
1326 $filterVal .= "2";
1327 break;
1328
1329 case 'Organization':
1330 $filterVal .= "3";
1331 break;
1332 }
1333 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1334 }
1335
5f35a2d9 1336 Civi::$statics[__CLASS__]['greeting'][$index] = CRM_Core_OptionGroup::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
6a488035
TO
1337 }
1338
5f35a2d9 1339 return Civi::$statics[__CLASS__]['greeting'][$index];
6a488035
TO
1340 }
1341
6a488035 1342 /**
d09edf64 1343 * Get all extensions.
6a488035
TO
1344 *
1345 * The static array extensions
1346 *
1347 * FIXME: This is called by civix but not by any core code. We
1348 * should provide an API call which civix can use instead.
1349 *
6a488035 1350 *
a6c01b45
CW
1351 * @return array
1352 * array($fullyQualifiedName => $label) list of extensions
6a488035
TO
1353 */
1354 public static function &getExtensions() {
1355 if (!self::$extensions) {
6542d699 1356 $compat = CRM_Extension_System::getCompatibilityInfo();
be2fb01f 1357 self::$extensions = [];
6a488035
TO
1358 $sql = '
1359 SELECT full_name, label
1360 FROM civicrm_extension
1361 WHERE is_active = 1
1362 ';
1363 $dao = CRM_Core_DAO::executeQuery($sql);
1364 while ($dao->fetch()) {
6542d699
TO
1365 if (!empty($compat[$dao->full_name]['force-uninstall'])) {
1366 continue;
1367 }
6a488035
TO
1368 self::$extensions[$dao->full_name] = $dao->label;
1369 }
1370 }
1371
1372 return self::$extensions;
1373 }
1374
f743a6eb 1375 /**
d09edf64 1376 * Get all options values.
f743a6eb
CW
1377 *
1378 * The static array option values is returned
1379 *
f743a6eb 1380 *
bbaf615e 1381 * @param string $optionGroupName
1382 * Name of option group
f743a6eb 1383 *
100fef9d 1384 * @param int $id
bbaf615e 1385 * @param string $condition
1386 * @param string $column
1387 * Whether to return 'name' or 'label'
f743a6eb 1388 *
a6c01b45 1389 * @return array
bbaf615e 1390 * array reference of all Option Values
f743a6eb 1391 */
bbaf615e 1392 public static function accountOptionValues($optionGroupName, $id = NULL, $condition = NULL, $column = 'label') {
1393 $cacheKey = $optionGroupName . '_' . $condition . '_' . $column;
f743a6eb 1394 if (empty(self::$accountOptionValues[$cacheKey])) {
bbaf615e 1395 self::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup::values($optionGroupName, FALSE, FALSE, FALSE, $condition, $column);
f743a6eb
CW
1396 }
1397 if ($id) {
914d3734 1398 return self::$accountOptionValues[$cacheKey][$id] ?? NULL;
f743a6eb
CW
1399 }
1400
1401 return self::$accountOptionValues[$cacheKey];
1402 }
1403
6a488035
TO
1404 /**
1405 * Fetch the list of active extensions of type 'module'
1406 *
5a4f6742
CW
1407 * @param bool $fresh
1408 * Whether to forcibly reload extensions list from canonical store.
6a488035 1409 *
a6c01b45
CW
1410 * @return array
1411 * array(array('prefix' => $, 'file' => $))
6a488035
TO
1412 */
1413 public static function getModuleExtensions($fresh = FALSE) {
1414 return CRM_Extension_System::singleton()->getMapper()->getActiveModuleFiles($fresh);
1415 }
dc428161 1416
dc428161 1417 /**
d09edf64 1418 * Get all tax rates.
dc428161 1419 *
1420 * The static array tax rates is returned
1421 *
a6c01b45
CW
1422 * @return array
1423 * array list of tax rates with the financial type
dc428161 1424 */
1425 public static function getTaxRates() {
27864d8a 1426 if (!isset(Civi::$statics[__CLASS__]['taxRates'])) {
be2fb01f
CW
1427 Civi::$statics[__CLASS__]['taxRates'] = [];
1428 $option = civicrm_api3('option_value', 'get', [
a38ebe6a
SL
1429 'sequential' => 1,
1430 'option_group_id' => 'account_relationship',
1431 'name' => 'Sales Tax Account is',
be2fb01f
CW
1432 ]);
1433 $value = [];
a38ebe6a 1434 if ($option['count'] !== 0) {
02b2d071
SL
1435 if ($option['count'] > 1) {
1436 foreach ($option['values'] as $opt) {
1437 $value[] = $opt['value'];
1438 }
1439 }
1440 else {
1441 $value[] = $option['values'][0]['value'];
1442 }
518fa0ee 1443 $where = 'AND efa.account_relationship IN (' . implode(', ', $value) . ' )';
a38ebe6a
SL
1444 }
1445 else {
1446 $where = '';
1447 }
dc428161 1448 $sql = "
1449 SELECT fa.tax_rate, efa.entity_id
1450 FROM civicrm_entity_financial_account efa
1451 INNER JOIN civicrm_financial_account fa ON fa.id = efa.financial_account_id
dc428161 1452 WHERE efa.entity_table = 'civicrm_financial_type'
a38ebe6a 1453 {$where}
dc428161 1454 AND fa.is_active = 1";
1455 $dao = CRM_Core_DAO::executeQuery($sql);
1456 while ($dao->fetch()) {
27864d8a 1457 Civi::$statics[__CLASS__]['taxRates'][$dao->entity_id] = $dao->tax_rate;
dc428161 1458 }
1459 }
1460
27864d8a 1461 return Civi::$statics[__CLASS__]['taxRates'];
dc428161 1462 }
96025800 1463
f61d1b83
AS
1464 /**
1465 * Get participant status class options.
1466 *
1467 * @return array
1468 */
1469 public static function emailOnHoldOptions() {
be2fb01f 1470 return [
f61d1b83
AS
1471 '0' => ts('No'),
1472 '1' => ts('On Hold Bounce'),
1473 '2' => ts('On Hold Opt Out'),
be2fb01f 1474 ];
f61d1b83
AS
1475 }
1476
b53c3468 1477 /**
1478 * Render the field options from the available pseudoconstant.
1479 *
1480 * Do not call this function directly or from untested code. Further cleanup is likely.
1481 *
1482 * @param array $pseudoconstant
1483 * @param array $params
1484 * @param string|null $localizeContext
1485 * @param string $context
1486 *
1487 * @return array|bool|mixed
1488 */
1489 public static function renderOptionsFromTablePseudoconstant($pseudoconstant, &$params = [], $localizeContext = NULL, $context = '') {
1490 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($pseudoconstant['table']);
1491 if (!class_exists($daoName)) {
1492 return FALSE;
1493 }
1494 // Get list of fields for the option table
1495 /* @var CRM_Core_DAO $dao * */
1496 $dao = new $daoName();
1497 $availableFields = array_keys($dao->fieldKeys());
1498
1499 $select = 'SELECT %1 AS id, %2 AS label';
1500 $from = 'FROM %3';
1501 $wheres = [];
1502 $order = 'ORDER BY %2';
1503
1504 // Use machine name in certain contexts
1505 if ($context === 'validate' || $context === 'match') {
1506 $nameField = $context === 'validate' ? 'labelColumn' : 'keyColumn';
1507 if (!empty($pseudoconstant['nameColumn'])) {
1508 $params[$nameField] = $pseudoconstant['nameColumn'];
1509 }
1510 elseif (in_array('name', $availableFields)) {
1511 $params[$nameField] = 'name';
1512 }
1513 }
1514
1515 // Use abbrColum if context is abbreviate
70c5cd97
CW
1516 if ($context === 'abbreviate' && !empty($pseudoconstant['abbrColumn'])) {
1517 $params['labelColumn'] = $pseudoconstant['abbrColumn'];
b53c3468 1518 }
1519
1520 // Condition param can be passed as an sql clause string or an array of clauses
1521 if (!empty($params['condition'])) {
1522 $wheres[] = implode(' AND ', (array) $params['condition']);
1523 }
1524 // onlyActive param will automatically filter on common flags
1525 if (!empty($params['onlyActive'])) {
1526 foreach (['is_active' => 1, 'is_deleted' => 0, 'is_test' => 0, 'is_hidden' => 0] as $flag => $val) {
1527 if (in_array($flag, $availableFields)) {
1528 $wheres[] = "$flag = $val";
1529 }
1530 }
1531 }
1532 // Filter domain specific options
1533 if (in_array('domain_id', $availableFields)) {
4f238b49 1534 $wheres[] = 'domain_id = ' . CRM_Core_Config::domainID() . ' OR domain_id is NULL';
b53c3468 1535 }
1536 $queryParams = [
1537 1 => [$params['keyColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES],
1538 2 => [$params['labelColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES],
1539 3 => [$pseudoconstant['table'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES],
1540 ];
1541 // Add orderColumn param
1542 if (!empty($params['orderColumn'])) {
1543 $queryParams[4] = [$params['orderColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES];
1544 $order = 'ORDER BY %4';
1545 }
1546 // Support no sorting if $params[orderColumn] is FALSE
1547 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
1548 $order = '';
1549 }
1550 // Default to 'weight' if that column exists
1551 elseif (in_array('weight', $availableFields)) {
1552 $order = "ORDER BY weight";
1553 }
1554
1555 $output = [];
1556 $query = "$select $from";
1557 if ($wheres) {
770d8a40 1558 $query .= " WHERE " . implode(' AND ', $wheres);
b53c3468 1559 }
1560 $query .= ' ' . $order;
1561 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
1562 while ($dao->fetch()) {
1563 $output[$dao->id] = $dao->label;
1564 }
1565 // Localize results
1566 if (!empty($params['localize']) || $pseudoconstant['table'] === 'civicrm_country' || $pseudoconstant['table'] === 'civicrm_state_province') {
3c4a4657
SP
1567 if ($pseudoconstant['table'] === 'civicrm_country') {
1568 $output = CRM_Core_BAO_Country::_defaultContactCountries($output);
1569 // avoid further sorting
1570 $order = '';
1571 }
1572 else {
1573 $I18nParams = [];
1574 if ($localizeContext) {
1575 $I18nParams['context'] = $localizeContext;
1576 }
1577 $i18n = CRM_Core_I18n::singleton();
1578 $i18n->localizeArray($output, $I18nParams);
b53c3468 1579 }
b53c3468 1580 // Maintain sort by label
1581 if ($order === 'ORDER BY %2') {
1582 $output = CRM_Utils_Array::asort($output);
1583 }
1584 }
1585
1586 return $output;
1587 }
1588
815facd4
CW
1589 /**
1590 * Convert multidimensional option list to flat array, if necessary
1591 *
1592 * Detect if an array of options is simple key/value pairs or a multidimensional array.
1593 * If the latter, convert to a flat array, as determined by $context.
1594 *
1595 * @param string|null $context
1596 * See https://docs.civicrm.org/dev/en/latest/framework/pseudoconstant/#context
1597 * @param array $options
1598 * List of options, each as a record of id+name+label.
1599 * Ex: [['id' => 123, 'name' => 'foo_bar', 'label' => 'Foo Bar']]
1600 */
3d2f86c5 1601 public static function formatArrayOptions($context, array &$options) {
815facd4
CW
1602 // Already flat; return keys/values according to context
1603 if (!isset($options[0]) || !is_array($options[0])) {
1604 // For validate context, machine names are expected in place of labels.
1605 // A flat array has no names so use the ids for both key and value.
1606 return $context === 'validate' ?
1607 array_combine(array_keys($options), array_keys($options)) :
1608 $options;
1609 }
1610 $result = [];
1611 $key = ($context === 'match') ? 'name' : 'id';
1612 $value = ($context === 'validate') ? 'name' : (($context === 'abbreviate') ? 'abbr' : 'label');
1613 foreach ($options as $option) {
1614 // Some fallbacks in case the array is missing a 'name' or 'label' or 'abbr'
1615 $id = $option[$key] ?? $option['id'] ?? $option['name'];
1616 $result[$id] = $option[$value] ?? $option['label'] ?? $option['name'];
1617 }
1618 return $result;
1619 }
1620
6a488035 1621}