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