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