3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
14 * Stores all constants and pseudo constants for CRM application.
16 * examples of constants are "Contact Type" which will always be either
17 * 'Individual', 'Household', 'Organization'.
19 * pseudo constants are entities from the database whose values rarely
20 * change. examples are list of countries, states, location types,
23 * currently we're getting the data from the underlying database. this
24 * will be reworked to use caching.
26 * Note: All pseudoconstants should be uninitialized or default to NULL.
27 * This provides greater consistency/predictability after flushing.
30 * @copyright CiviCRM LLC https://civicrm.org/licensing
32 class CRM_Core_PseudoConstant
{
35 * Static cache for pseudoconstant arrays.
38 private static $cache;
43 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
45 private static $activityType;
51 private static $stateProvince;
57 private static $county;
60 * States/provinces abbreviations
63 private static $stateProvinceAbbreviation = [];
69 private static $country;
75 private static $countryIsoCode;
80 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
82 private static $group;
88 private static $relationshipType = [];
91 * Civicrm groups that are not smart groups
94 private static $staticGroup;
100 private static $currencyCode;
106 private static $paymentProcessor;
109 * Payment processor types
112 private static $paymentProcessorType;
118 private static $worldRegions;
123 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
125 private static $activityStatus;
131 private static $visibility;
137 private static $greeting;
140 * Extensions of type module
143 private static $extensions;
146 * Financial Account Type
149 private static $accountOptionValues;
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/
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.
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
179 * array on success, FALSE on error.
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
192 'localize' => $localizeDefault,
193 'onlyActive' => !($context == 'validate' ||
$context == 'get'),
195 'context' => $context,
197 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName($daoName);
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);
210 // Core field: load schema
211 $dao = new $daoName();
212 $fieldSpec = $dao->getFieldSpec($fieldName);
214 // Return false if field doesn't exist.
215 if (empty($fieldSpec)) {
219 // Ensure we have the canonical name for this field
220 $fieldName = $fieldSpec['name'] ??
$fieldName;
222 if (!empty($fieldSpec['pseudoconstant'])) {
223 $pseudoconstant = $fieldSpec['pseudoconstant'];
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;
233 // Merge params with schema defaults
235 'condition' => $pseudoconstant['condition'] ??
[],
236 'keyColumn' => $pseudoconstant['keyColumn'] ??
NULL,
237 'labelColumn' => $pseudoconstant['labelColumn'] ??
NULL,
240 // Fetch option group from option_value table
241 if (!empty($pseudoconstant['optionGroupName'])) {
242 if ($context == 'validate') {
243 $params['labelColumn'] = 'name';
245 if ($context == 'match') {
246 $params['keyColumn'] = 'name';
248 // Call our generic fn for retrieving from the option_value table
249 $options = CRM_Core_OptionGroup
::values(
250 $pseudoconstant['optionGroupName'],
254 $params['condition'] ?
' AND ' . implode(' AND ', (array) $params['condition']) : NULL,
255 $params['labelColumn'] ?
$params['labelColumn'] : 'label',
256 $params['onlyActive'],
258 $params['keyColumn'] ?
$params['keyColumn'] : 'value',
259 !empty($params['orderColumn']) ?
$params['orderColumn'] : 'weight'
261 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $options, $params);
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.
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];
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;
280 return $flip ?
array_flip($output) : $output;
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;
290 // If we're still here, it's an error. Return FALSE.
295 * Fetch the translated label for a field given its key.
297 * @param string $baoName
298 * @param string $fieldName
299 * @param string|int $key
301 * TODO: Accept multivalued input?
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
308 public static function getLabel($baoName, $fieldName, $key) {
309 $values = $baoName::buildOptions($fieldName, 'get');
310 if ($values === FALSE) {
313 return $values[$key] ??
NULL;
317 * Fetch the machine name for a field given its key.
319 * @param string $baoName
320 * @param string $fieldName
321 * @param string|int $key
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
328 public static function getName($baoName, $fieldName, $key) {
329 $values = $baoName::buildOptions($fieldName, 'validate');
330 if ($values === FALSE) {
333 return $values[$key] ??
NULL;
337 * Fetch the key for a field option given its name.
339 * @param string $baoName
340 * @param string $fieldName
341 * @param string|int $value
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
348 public static function getKey($baoName, $fieldName, $value) {
349 $values = $baoName::buildOptions($fieldName, 'validate');
350 if ($values === FALSE) {
353 return CRM_Utils_Array
::key($value, $values);
357 * Lookup the admin page at which a field's option list can be edited
359 * @return string|null
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'];
366 // For everything else...
367 elseif (!empty($fieldSpec['pseudoconstant']['table'])) {
368 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($fieldSpec['pseudoconstant']['table']);
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
378 return CRM_Core_DAO
::singleValueQuery($sql);
384 * @deprecated generic populate method.
385 * All pseudoconstant functions that use this method are also @deprecated
387 * The static array $var is populated from the db
388 * using the <b>$name DAO</b>.
390 * Note: any database errors will be trapped by the DAO.
393 * The associative array we will fill.
394 * @param string $name
395 * The name of the DAO.
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.
405 * @param bool $orderby
411 public static function populate(
416 $filter = 'is_active',
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)) {
429 /* @var CRM_Core_DAO $object */
430 $object = new $name();
432 $object->selectAdd();
433 $object->selectAdd("$key, $retrieve");
435 $object->whereAdd($condition);
439 $object->orderBy($retrieve);
442 $object->orderBy($orderby);
446 $object->$filter = 1;
447 $aclClauses = array_filter($name::getSelectWhereClause());
448 foreach ($aclClauses as $clause) {
449 $object->whereAdd($clause);
455 while ($object->fetch()) {
456 $var[$object->$key] = $object->$retrieve;
459 $cache->set($cacheKey, $var);
463 * Flush given pseudoconstant so it can be reread from db.
464 * nex time it's requested.
466 * @param bool|string $name pseudoconstant to be flushed
468 public static function flush($name = 'cache') {
469 if (isset(self
::$
$name)) {
472 if ($name == 'cache') {
473 CRM_Core_OptionGroup
::flushAll();
474 if (isset(\Civi
::$statics[__CLASS__
])) {
475 unset(\Civi
::$statics[__CLASS__
]);
481 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
483 * Get all Activty types.
485 * The static array activityType is returned
489 * array reference of all activity types.
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;
503 if (NULL === self
::$activityType) {
504 self
::$activityType = [];
507 if (!isset(self
::$activityType[$index]) ||
$reset) {
510 $condition = 'AND filter = 0';
512 $componentClause = " v.component_id IS NULL";
513 if ($onlyComponentActivities) {
514 $componentClause = " v.component_id IS NOT NULL";
518 $compInfo = CRM_Core_Component
::getEnabledComponents();
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
;
528 elseif ($compName == 'CiviCampaign') {
529 if ($includeCampaignActivities) {
530 $componentIds[] = $compObj->componentID
;
534 $componentIds[] = $compObj->componentID
;
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 ) )";
545 $condition = $condition . ' AND ' . $componentClause;
547 self
::$activityType[$index] = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
549 return self
::$activityType[$index];
553 * Get all the State/Province from database.
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.
559 * Note: any database errors will be trapped by the DAO.
562 * @param bool|int $id - Optional id to return
567 * array reference of all State/Provinces.
569 public static function &stateProvince($id = FALSE, $limit = TRUE) {
570 if (($id && empty(self
::$stateProvince[$id])) ||
!self
::$stateProvince ||
!$id) {
571 $whereClause = FALSE;
573 $countryIsoCodes = self
::countryIsoCode();
574 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
576 foreach ($limitCodes as $code) {
577 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
579 if (!empty($limitIds)) {
580 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
583 $whereClause = FALSE;
586 self
::populate(self
::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
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',
595 self
::$stateProvince = CRM_Utils_Array
::asort(self
::$stateProvince);
599 if (array_key_exists($id, self
::$stateProvince)) {
600 return self
::$stateProvince[$id];
607 return self
::$stateProvince;
611 * Get all the State/Province abbreviations from the database.
613 * Same as above, except gets the abbreviations instead of the names.
616 * @param bool|int $id - Optional id to return
621 * array reference of all State/Province abbreviations.
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
635 self
::$stateProvinceAbbreviation[$id] = CRM_Core_DAO
::singleValueQuery($query, $params);
637 return self
::$stateProvinceAbbreviation[$id];
640 $whereClause = FALSE;
643 $countryIsoCodes = self
::countryIsoCode();
644 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
646 foreach ($limitCodes as $code) {
647 $tmpArray = array_keys($countryIsoCodes, $code);
649 if (!empty($tmpArray)) {
650 $limitIds[] = array_shift($tmpArray);
653 if (!empty($limitIds)) {
654 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
657 self
::populate(self
::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
660 return self
::$stateProvinceAbbreviation;
664 * Get all the State/Province abbreviations from the database for the specified country.
666 * @param int $countryID
669 * array of all State/Province abbreviations for the given country.
671 public static function stateProvinceAbbreviationForCountry($countryID) {
672 if (!isset(\Civi
::$statics[__CLASS__
]['stateProvinceAbbreviationForCountry'][$countryID])) {
673 \Civi
::$statics[__CLASS__
]['stateProvinceAbbreviationForCountry'][$countryID] = [];
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];
680 * Get all the State/Province abbreviations from the database for the default country.
683 * array of all State/Province abbreviations for the given country.
685 public static function stateProvinceAbbreviationForDefaultCountry() {
686 return CRM_Core_PseudoConstant
::stateProvinceAbbreviationForCountry(Civi
::settings()->get('defaultContactCountry'));
690 * Get all the countries from database.
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.
696 * Note: any database errors will be trapped by the DAO.
699 * @param bool|int $id - Optional id to return
701 * @param bool $applyLimit
704 * array reference of all countries.
706 public static function country($id = FALSE, $applyLimit = TRUE) {
707 if (($id && empty(self
::$country[$id])) ||
!self
::$country ||
!$id) {
709 $config = CRM_Core_Config
::singleton();
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)) {
719 $config->countryLimit
=> 1,
723 $limitCodes = array_intersect(self
::countryIsoCode(), $limitCodes);
726 if (count($limitCodes)) {
727 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
733 self
::populate(self
::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
735 // if default country is set, percolate it to the top
736 if (CRM_Core_BAO_Country
::defaultContactCountry()) {
737 $countryIsoCodes = self
::countryIsoCode();
738 $defaultID = array_search(CRM_Core_BAO_Country
::defaultContactCountry(), $countryIsoCodes);
739 if ($defaultID !== FALSE) {
740 $default[$defaultID] = self
::$country[$defaultID] ??
NULL;
741 self
::$country = $default + self
::$country;
745 // localise the country names if in an non-en_US locale
746 $tsLocale = CRM_Core_I18n
::getLocale();
747 if ($tsLocale != '' and $tsLocale != 'en_US') {
748 $i18n = CRM_Core_I18n
::singleton();
749 $i18n->localizeArray(self
::$country, [
750 'context' => 'country',
752 self
::$country = CRM_Utils_Array
::asort(self
::$country);
756 if (array_key_exists($id, self
::$country)) {
757 return self
::$country[$id];
763 return self
::$country;
767 * Get all the country ISO Code abbreviations from the database.
769 * The static array countryIsoCode is returned, and if it's
770 * called the first time, the <b>Country DAO</b> is used
771 * to get all the countries' ISO codes.
773 * Note: any database errors will be trapped by the DAO.
779 * array reference of all country ISO codes.
781 public static function &countryIsoCode($id = FALSE) {
782 if (!self
::$countryIsoCode) {
783 self
::populate(self
::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
786 if (array_key_exists($id, self
::$countryIsoCode)) {
787 return self
::$countryIsoCode[$id];
790 return CRM_Core_DAO
::$_nullObject;
793 return self
::$countryIsoCode;
797 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
799 * Get all groups from database
801 * The static array group is returned, and if it's
802 * called the first time, the <b>Group DAO</b> is used
803 * to get all the groups.
805 * Note: any database errors will be trapped by the DAO.
807 * @param string $groupType
808 * Type of group(Access/Mailing).
809 * @param bool $excludeHidden
810 * Exclude hidden groups.
814 * array reference of all groups.
816 public static function allGroup($groupType = NULL, $excludeHidden = TRUE) {
817 if ($groupType === 'validate') {
818 // validate gets passed through from getoptions. Handle in the deprecated
819 // fn rather than change the new pattern.
822 $condition = CRM_Contact_BAO_Group
::groupTypeCondition($groupType, $excludeHidden);
823 $groupKey = ($groupType ?
$groupType : 'null') . !empty($excludeHidden);
825 if (!isset(Civi
::$statics[__CLASS__
]['groups']['allGroup'][$groupKey])) {
826 self
::populate(Civi
::$statics[__CLASS__
]['groups']['allGroup'][$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
828 return Civi
::$statics[__CLASS__
]['groups']['allGroup'][$groupKey];
832 * Get all permissioned groups from database.
834 * The static array group is returned, and if it's
835 * called the first time, the <b>Group DAO</b> is used
836 * to get all the groups.
838 * Note: any database errors will be trapped by the DAO.
840 * @param string $groupType
841 * Type of group(Access/Mailing).
842 * @param bool $excludeHidden
843 * Exclude hidden groups.
847 * array reference of all groups.
849 public static function group($groupType = NULL, $excludeHidden = TRUE) {
850 return CRM_Core_Permission
::group($groupType, $excludeHidden);
854 * Fetch groups in a nested format suitable for use in select form element.
855 * @param bool $checkPermissions
856 * @param string|null $groupType
857 * @param bool $excludeHidden
860 public static function nestedGroup($checkPermissions = TRUE, $groupType = NULL, $excludeHidden = TRUE) {
861 $groups = $checkPermissions ? self
::group($groupType, $excludeHidden) : self
::allGroup($groupType, $excludeHidden);
862 return CRM_Contact_BAO_Group
::getGroupsHierarchy($groups, NULL, ' ', TRUE);
866 * Get all permissioned groups from database.
868 * The static array group is returned, and if it's
869 * called the first time, the <b>Group DAO</b> is used
870 * to get all the groups.
872 * Note: any database errors will be trapped by the DAO.
875 * @param bool $onlyPublic
876 * @param null $groupType
877 * @param bool $excludeHidden
880 * array reference of all groups.
882 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
883 if (!self
::$staticGroup) {
884 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
886 $condition .= " AND visibility != 'User and User Admin Only'";
890 $condition .= ' AND ' . CRM_Contact_BAO_Group
::groupTypeCondition($groupType);
893 if ($excludeHidden) {
894 $condition .= ' AND is_hidden != 1 ';
897 self
::populate(self
::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
900 return self
::$staticGroup;
904 * Get all Relationship Types from database.
906 * The static array group is returned, and if it's
907 * called the first time, the <b>RelationshipType DAO</b> is used
908 * to get all the relationship types.
910 * Note: any database errors will be trapped by the DAO.
912 * @param string $valueColumnName
913 * Db column name/label.
915 * Reset relationship types if true.
916 * @param bool $isActive
917 * Filter by is_active. NULL to disable.
920 * array reference of all relationship types.
922 public static function relationshipType($valueColumnName = 'label', $reset = FALSE, $isActive = 1) {
923 $cacheKey = $valueColumnName . '::' . $isActive;
924 if (!isset(self
::$relationshipType[$cacheKey]) ||
$reset) {
925 self
::$relationshipType[$cacheKey] = [];
927 //now we have name/label columns CRM-3336
928 $column_a_b = "{$valueColumnName}_a_b";
929 $column_b_a = "{$valueColumnName}_b_a";
931 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
932 $relationshipTypeDAO->selectAdd();
933 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
934 if ($isActive !== NULL) {
935 $relationshipTypeDAO->is_active
= $isActive;
937 $relationshipTypeDAO->find();
938 while ($relationshipTypeDAO->fetch()) {
940 self
::$relationshipType[$cacheKey][$relationshipTypeDAO->id
] = [
941 'id' => $relationshipTypeDAO->id
,
942 $column_a_b => $relationshipTypeDAO->$column_a_b,
943 $column_b_a => $relationshipTypeDAO->$column_b_a,
944 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
945 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
946 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
947 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
952 return self
::$relationshipType[$cacheKey];
956 * Name => Label pairs for all relationship types
960 public static function relationshipTypeOptions() {
961 $relationshipTypes = [];
962 $relationshipLabels = self
::relationshipType();
963 foreach (self
::relationshipType('name') as $id => $type) {
964 $relationshipTypes[$type['name_a_b']] = $relationshipLabels[$id]['label_a_b'];
965 if ($type['name_b_a'] && $type['name_b_a'] != $type['name_a_b']) {
966 $relationshipTypes[$type['name_b_a']] = $relationshipLabels[$id]['label_b_a'];
969 return $relationshipTypes;
973 * Get all the ISO 4217 currency codes
975 * so far, we use this for validation only, so there's no point of putting this into the database
979 * array reference of all currency codes
981 public static function ¤cyCode() {
982 if (!self
::$currencyCode) {
984 $query = "SELECT name FROM civicrm_currency";
985 $dao = CRM_Core_DAO
::executeQuery($query);
987 while ($dao->fetch()) {
988 self
::$currencyCode[] = $dao->name
;
991 return self
::$currencyCode;
995 * Get all the County from database.
997 * The static array county is returned, and if it's
998 * called the first time, the <b>County DAO</b> is used
999 * to get all the Counties.
1001 * Note: any database errors will be trapped by the DAO.
1004 * @param bool|int $id - Optional id to return
1007 * array reference of all Counties
1009 public static function &county($id = FALSE) {
1010 if (!self
::$county) {
1012 $config = CRM_Core_Config
::singleton();
1013 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1014 self
::populate(self
::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1017 if (array_key_exists($id, self
::$county)) {
1018 return self
::$county[$id];
1021 return CRM_Core_DAO
::$_nullObject;
1024 return self
::$county;
1028 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1029 * Get all active payment processors
1031 * The static array paymentProcessor is returned
1035 * Get payment processors - default is to get only active ones.
1037 * Get test payment processors.
1039 * @param null $additionalCond
1042 * array of all payment processors
1044 public static function paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1045 $condition = "is_test = ";
1046 $condition .= ($test) ?
'1' : '0';
1048 if ($additionalCond) {
1049 $condition .= " AND ( $additionalCond ) ";
1052 // CRM-7178. Make sure we only include payment processors valid in this
1054 $condition .= " AND domain_id = " . CRM_Core_Config
::domainID();
1056 $cacheKey = $condition . '_' . (int) $all;
1057 if (!isset(self
::$paymentProcessor[$cacheKey])) {
1058 self
::populate(self
::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1061 return self
::$paymentProcessor[$cacheKey];
1065 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1067 * The static array paymentProcessorType is returned
1071 * Get payment processors - default is to get only active ones.
1074 * @param string $return
1077 * array of all payment processor types
1079 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1080 $cacheKey = $id . '_' . $return;
1081 if (empty(self
::$paymentProcessorType[$cacheKey])) {
1082 self
::populate(self
::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1084 if ($id && !empty(self
::$paymentProcessorType[$cacheKey][$id])) {
1085 return self
::$paymentProcessorType[$cacheKey][$id];
1087 return self
::$paymentProcessorType[$cacheKey];
1091 * Get all the World Regions from Database.
1097 * array reference of all World Regions
1099 public static function &worldRegion($id = FALSE) {
1100 if (!self
::$worldRegions) {
1101 self
::populate(self
::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1105 if (array_key_exists($id, self
::$worldRegions)) {
1106 return self
::$worldRegions[$id];
1109 return CRM_Core_DAO
::$_nullObject;
1113 return self
::$worldRegions;
1117 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1119 * Get all Activity Statuses.
1121 * The static array activityStatus is returned
1124 * @param string $column
1127 * array reference of all activity statuses
1129 public static function &activityStatus($column = 'label') {
1130 if (NULL === self
::$activityStatus) {
1131 self
::$activityStatus = [];
1133 if (!array_key_exists($column, self
::$activityStatus)) {
1134 self
::$activityStatus[$column] = [];
1136 self
::$activityStatus[$column] = CRM_Core_OptionGroup
::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1139 return self
::$activityStatus[$column];
1143 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1145 * Get all Visibility levels.
1147 * The static array visibility is returned
1150 * @param string $column
1153 * array reference of all Visibility levels.
1155 public static function &visibility($column = 'label') {
1156 if (!isset(self
::$visibility)) {
1157 self
::$visibility = [];
1160 if (!isset(self
::$visibility[$column])) {
1161 self
::$visibility[$column] = CRM_Core_OptionGroup
::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1164 return self
::$visibility[$column];
1168 * @param int $countryID
1169 * @param string $field
1173 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1174 static $_cache = NULL;
1176 $cacheKey = "{$countryID}_{$field}";
1181 if (!empty($_cache[$cacheKey])) {
1182 return $_cache[$cacheKey];
1186 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1187 FROM civicrm_state_province
1188 WHERE country_id = %1
1197 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1200 while ($dao->fetch()) {
1201 $result[$dao->id
] = $dao->name
;
1204 // localise the stateProvince names if in an non-en_US locale
1205 $config = CRM_Core_Config
::singleton();
1206 $tsLocale = CRM_Core_I18n
::getLocale();
1207 if ($tsLocale != '' and $tsLocale != 'en_US') {
1208 $i18n = CRM_Core_I18n
::singleton();
1209 $i18n->localizeArray($result, [
1210 'context' => 'province',
1212 $result = CRM_Utils_Array
::asort($result);
1215 $_cache[$cacheKey] = $result;
1217 CRM_Utils_Hook
::buildStateProvinceForCountry($countryID, $result);
1223 * @param int $stateID
1227 public static function &countyForState($stateID) {
1228 if (is_array($stateID)) {
1229 $states = implode(", ", $stateID);
1231 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1233 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1234 WHERE civicrm_county.state_province_id in ( $states )
1235 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1237 $dao = CRM_Core_DAO
::executeQuery($query);
1240 while ($dao->fetch()) {
1241 $result[$dao->id
] = $dao->abbreviation
. ': ' . $dao->name
;
1246 static $_cache = NULL;
1248 $cacheKey = "{$stateID}_name";
1253 if (!empty($_cache[$cacheKey])) {
1254 return $_cache[$cacheKey];
1258 SELECT civicrm_county.name name, civicrm_county.id id
1260 WHERE state_province_id = %1
1269 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1272 while ($dao->fetch()) {
1273 $result[$dao->id
] = $dao->name
;
1281 * Given a state ID return the country ID, this allows
1282 * us to populate forms and values for downstream code
1284 * @param int $stateID
1287 * the country id that the state belongs to
1289 public static function countryIDForStateID($stateID) {
1290 if (empty($stateID)) {
1296 FROM civicrm_state_province
1299 $params = [1 => [$stateID, 'Integer']];
1301 return CRM_Core_DAO
::singleValueQuery($query, $params);
1305 * Get all types of Greetings.
1307 * The static array of greeting is returned
1311 * Get All Email Greetings - default is to get only active ones.
1313 * @param string $columnName
1316 * array reference of all greetings.
1318 public static function greeting($filter, $columnName = 'label') {
1319 if (!isset(Civi
::$statics[__CLASS__
]['greeting'])) {
1320 Civi
::$statics[__CLASS__
]['greeting'] = [];
1323 $index = $filter['greeting_type'] . '_' . $columnName;
1325 // also add contactType to the array
1326 $contactType = $filter['contact_type'] ??
NULL;
1328 $index .= '_' . $contactType;
1331 if (empty(Civi
::$statics[__CLASS__
]['greeting'][$index])) {
1332 $filterCondition = NULL;
1334 $filterVal = 'v.filter =';
1335 switch ($contactType) {
1344 case 'Organization':
1348 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1351 Civi
::$statics[__CLASS__
]['greeting'][$index] = CRM_Core_OptionGroup
::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1354 return Civi
::$statics[__CLASS__
]['greeting'][$index];
1358 * Get all extensions.
1360 * The static array extensions
1362 * FIXME: This is called by civix but not by any core code. We
1363 * should provide an API call which civix can use instead.
1367 * array($fullyQualifiedName => $label) list of extensions
1369 public static function &getExtensions() {
1370 if (!self
::$extensions) {
1371 $compat = CRM_Extension_System
::getCompatibilityInfo();
1372 self
::$extensions = [];
1374 SELECT full_name, label
1375 FROM civicrm_extension
1378 $dao = CRM_Core_DAO
::executeQuery($sql);
1379 while ($dao->fetch()) {
1380 if (!empty($compat[$dao->full_name
]['force-uninstall'])) {
1383 self
::$extensions[$dao->full_name
] = $dao->label
;
1387 return self
::$extensions;
1391 * Get all options values.
1393 * The static array option values is returned
1396 * @param string $optionGroupName
1397 * Name of option group
1400 * @param string $condition
1401 * @param string $column
1402 * Whether to return 'name' or 'label'
1405 * array reference of all Option Values
1407 public static function accountOptionValues($optionGroupName, $id = NULL, $condition = NULL, $column = 'label') {
1408 $cacheKey = $optionGroupName . '_' . $condition . '_' . $column;
1409 if (empty(self
::$accountOptionValues[$cacheKey])) {
1410 self
::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup
::values($optionGroupName, FALSE, FALSE, FALSE, $condition, $column);
1413 return self
::$accountOptionValues[$cacheKey][$id] ??
NULL;
1416 return self
::$accountOptionValues[$cacheKey];
1420 * Fetch the list of active extensions of type 'module'
1422 * @param bool $fresh
1423 * Whether to forcibly reload extensions list from canonical store.
1426 * array(array('prefix' => $, 'file' => $))
1428 public static function getModuleExtensions($fresh = FALSE) {
1429 return CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles($fresh);
1433 * Get all tax rates.
1435 * The static array tax rates is returned
1438 * array list of tax rates with the financial type
1440 public static function getTaxRates() {
1441 if (!isset(Civi
::$statics[__CLASS__
]['taxRates'])) {
1442 Civi
::$statics[__CLASS__
]['taxRates'] = [];
1443 $option = civicrm_api3('option_value', 'get', [
1445 'option_group_id' => 'account_relationship',
1446 'name' => 'Sales Tax Account is',
1449 if ($option['count'] !== 0) {
1450 if ($option['count'] > 1) {
1451 foreach ($option['values'] as $opt) {
1452 $value[] = $opt['value'];
1456 $value[] = $option['values'][0]['value'];
1458 $where = 'AND efa.account_relationship IN (' . implode(', ', $value) . ' )';
1464 SELECT fa.tax_rate, efa.entity_id
1465 FROM civicrm_entity_financial_account efa
1466 INNER JOIN civicrm_financial_account fa ON fa.id = efa.financial_account_id
1467 WHERE efa.entity_table = 'civicrm_financial_type'
1469 AND fa.is_active = 1";
1470 $dao = CRM_Core_DAO
::executeQuery($sql);
1471 while ($dao->fetch()) {
1472 Civi
::$statics[__CLASS__
]['taxRates'][$dao->entity_id
] = $dao->tax_rate
;
1476 return Civi
::$statics[__CLASS__
]['taxRates'];
1480 * Get participant status class options.
1484 public static function emailOnHoldOptions() {
1487 '1' => ts('On Hold Bounce'),
1488 '2' => ts('On Hold Opt Out'),
1493 * Render the field options from the available pseudoconstant.
1495 * Do not call this function directly or from untested code. Further cleanup is likely.
1497 * @param array $pseudoconstant
1498 * @param array $params
1499 * @param string|null $localizeContext
1500 * @param string $context
1502 * @return array|bool|mixed
1504 public static function renderOptionsFromTablePseudoconstant($pseudoconstant, &$params = [], $localizeContext = NULL, $context = '') {
1505 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($pseudoconstant['table']);
1506 if (!class_exists($daoName)) {
1509 // Get list of fields for the option table
1510 /* @var CRM_Core_DAO $dao * */
1511 $dao = new $daoName();
1512 $availableFields = array_keys($dao->fieldKeys());
1514 $select = 'SELECT %1 AS id, %2 AS label';
1517 $order = 'ORDER BY %2';
1519 // Use machine name in certain contexts
1520 if ($context === 'validate' ||
$context === 'match') {
1521 $nameField = $context === 'validate' ?
'labelColumn' : 'keyColumn';
1522 if (!empty($pseudoconstant['nameColumn'])) {
1523 $params[$nameField] = $pseudoconstant['nameColumn'];
1525 elseif (in_array('name', $availableFields)) {
1526 $params[$nameField] = 'name';
1530 // Use abbrColum if context is abbreviate
1531 if ($context === 'abbreviate' && (in_array('abbreviation', $availableFields) ||
!empty($pseudoconstant['abbrColumn']))) {
1532 $params['labelColumn'] = $pseudoconstant['abbrColumn'] ??
'abbreviation';
1535 // Condition param can be passed as an sql clause string or an array of clauses
1536 if (!empty($params['condition'])) {
1537 $wheres[] = implode(' AND ', (array) $params['condition']);
1539 // onlyActive param will automatically filter on common flags
1540 if (!empty($params['onlyActive'])) {
1541 foreach (['is_active' => 1, 'is_deleted' => 0, 'is_test' => 0, 'is_hidden' => 0] as $flag => $val) {
1542 if (in_array($flag, $availableFields)) {
1543 $wheres[] = "$flag = $val";
1547 // Filter domain specific options
1548 if (in_array('domain_id', $availableFields)) {
1549 $wheres[] = 'domain_id = ' . CRM_Core_Config
::domainID() . ' OR domain_id is NULL';
1552 1 => [$params['keyColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
],
1553 2 => [$params['labelColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
],
1554 3 => [$pseudoconstant['table'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
],
1556 // Add orderColumn param
1557 if (!empty($params['orderColumn'])) {
1558 $queryParams[4] = [$params['orderColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
];
1559 $order = 'ORDER BY %4';
1561 // Support no sorting if $params[orderColumn] is FALSE
1562 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
1565 // Default to 'weight' if that column exists
1566 elseif (in_array('weight', $availableFields)) {
1567 $order = "ORDER BY weight";
1571 $query = "$select $from";
1573 $query .= " WHERE " . implode(' AND ', $wheres);
1575 $query .= ' ' . $order;
1576 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
1577 while ($dao->fetch()) {
1578 $output[$dao->id
] = $dao->label
;
1581 if (!empty($params['localize']) ||
$pseudoconstant['table'] === 'civicrm_country' ||
$pseudoconstant['table'] === 'civicrm_state_province') {
1583 if ($localizeContext) {
1584 $I18nParams['context'] = $localizeContext;
1586 $i18n = CRM_Core_I18n
::singleton();
1587 $i18n->localizeArray($output, $I18nParams);
1588 // Maintain sort by label
1589 if ($order === 'ORDER BY %2') {
1590 $output = CRM_Utils_Array
::asort($output);