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