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,
198 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName($daoName);
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);
211 // Core field: load schema
212 $dao = new $daoName();
213 $fieldSpec = $dao->getFieldSpec($fieldName);
215 // Return false if field doesn't exist.
216 if (empty($fieldSpec)) {
220 // Ensure we have the canonical name for this field
221 $fieldName = $fieldSpec['name'] ??
$fieldName;
223 if (!empty($fieldSpec['pseudoconstant'])) {
224 $pseudoconstant = $fieldSpec['pseudoconstant'];
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;
234 // Merge params with schema defaults
236 'keyColumn' => $pseudoconstant['keyColumn'] ??
NULL,
237 'labelColumn' => $pseudoconstant['labelColumn'] ??
NULL,
239 if (!empty($pseudoconstant['condition'])) {
240 $params['condition'] = array_merge((array) $pseudoconstant['condition'], (array) $params['condition']);
243 // Fetch option group from option_value table
244 if (!empty($pseudoconstant['optionGroupName'])) {
245 if ($context == 'validate') {
246 $params['labelColumn'] = 'name';
248 if ($context == 'match') {
249 $params['keyColumn'] = 'name';
251 // Call our generic fn for retrieving from the option_value table
252 $options = CRM_Core_OptionGroup
::values(
253 $pseudoconstant['optionGroupName'],
257 $params['condition'] ?
' AND ' . implode(' AND ', (array) $params['condition']) : NULL,
258 $params['labelColumn'] ?
$params['labelColumn'] : 'label',
259 $params['onlyActive'],
261 $params['keyColumn'] ?
$params['keyColumn'] : 'value',
262 !empty($params['orderColumn']) ?
$params['orderColumn'] : 'weight'
264 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $options, $params);
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.
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];
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;
283 return $flip ?
array_flip($output) : $output;
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;
293 // If we're still here, it's an error. Return FALSE.
298 * Fetch the translated label for a field given its key.
300 * @param string $baoName
301 * @param string $fieldName
302 * @param string|int $key
304 * TODO: Accept multivalued input?
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
311 public static function getLabel($baoName, $fieldName, $key) {
312 $values = $baoName::buildOptions($fieldName, 'get');
313 if ($values === FALSE) {
316 return $values[$key] ??
NULL;
320 * Fetch the machine name for a field given its key.
322 * @param string $baoName
323 * @param string $fieldName
324 * @param string|int $key
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
331 public static function getName($baoName, $fieldName, $key) {
332 $values = $baoName::buildOptions($fieldName, 'validate');
333 if ($values === FALSE) {
336 return $values[$key] ??
NULL;
340 * Fetch the key for a field option given its name.
342 * @param string $baoName
343 * @param string $fieldName
344 * @param string|int $value
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
351 public static function getKey($baoName, $fieldName, $value) {
352 $values = $baoName::buildOptions($fieldName, 'validate');
353 if ($values === FALSE) {
356 return CRM_Utils_Array
::key($value, $values);
360 * Lookup the admin page at which a field's option list can be edited
362 * @return string|null
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'];
369 // For everything else...
370 elseif (!empty($fieldSpec['pseudoconstant']['table'])) {
371 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($fieldSpec['pseudoconstant']['table']);
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
381 return CRM_Core_DAO
::singleValueQuery($sql);
387 * @deprecated generic populate method.
388 * All pseudoconstant functions that use this method are also @deprecated
390 * The static array $var is populated from the db
391 * using the <b>$name DAO</b>.
393 * Note: any database errors will be trapped by the DAO.
396 * The associative array we will fill.
397 * @param string $name
398 * The name of the DAO.
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.
408 * @param bool $orderby
414 public static function populate(
419 $filter = 'is_active',
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)) {
432 /* @var CRM_Core_DAO $object */
433 $object = new $name();
435 $object->selectAdd();
436 $object->selectAdd("$key, $retrieve");
438 $object->whereAdd($condition);
442 $object->orderBy($retrieve);
445 $object->orderBy($orderby);
449 $object->$filter = 1;
450 $aclClauses = array_filter($name::getSelectWhereClause());
451 foreach ($aclClauses as $clause) {
452 $object->whereAdd($clause);
458 while ($object->fetch()) {
459 $var[$object->$key] = $object->$retrieve;
462 $cache->set($cacheKey, $var);
466 * Flush given pseudoconstant so it can be reread from db.
467 * nex time it's requested.
469 * @param bool|string $name pseudoconstant to be flushed
471 public static function flush($name = 'cache') {
472 if (isset(self
::$
$name)) {
475 if ($name == 'cache') {
476 CRM_Core_OptionGroup
::flushAll();
477 if (isset(\Civi
::$statics[__CLASS__
])) {
478 unset(\Civi
::$statics[__CLASS__
]);
484 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
486 * Get all Activty types.
488 * The static array activityType is returned
492 * array reference of all activity types.
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;
506 if (NULL === self
::$activityType) {
507 self
::$activityType = [];
510 if (!isset(self
::$activityType[$index]) ||
$reset) {
513 $condition = 'AND filter = 0';
515 $componentClause = " v.component_id IS NULL";
516 if ($onlyComponentActivities) {
517 $componentClause = " v.component_id IS NOT NULL";
521 $compInfo = CRM_Core_Component
::getEnabledComponents();
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
;
531 elseif ($compName == 'CiviCampaign') {
532 if ($includeCampaignActivities) {
533 $componentIds[] = $compObj->componentID
;
537 $componentIds[] = $compObj->componentID
;
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 ) )";
548 $condition = $condition . ' AND ' . $componentClause;
550 self
::$activityType[$index] = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
552 return self
::$activityType[$index];
556 * Get all the State/Province from database.
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.
562 * Note: any database errors will be trapped by the DAO.
565 * @param bool|int $id - Optional id to return
570 * array reference of all State/Provinces.
572 public static function &stateProvince($id = FALSE, $limit = TRUE) {
573 if (($id && empty(self
::$stateProvince[$id])) ||
!self
::$stateProvince ||
!$id) {
574 $whereClause = FALSE;
576 $countryIsoCodes = self
::countryIsoCode();
577 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
579 foreach ($limitCodes as $code) {
580 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
582 if (!empty($limitIds)) {
583 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
586 $whereClause = FALSE;
589 self
::populate(self
::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
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',
598 self
::$stateProvince = CRM_Utils_Array
::asort(self
::$stateProvince);
602 if (array_key_exists($id, self
::$stateProvince)) {
603 return self
::$stateProvince[$id];
610 return self
::$stateProvince;
614 * Get all the State/Province abbreviations from the database.
616 * Same as above, except gets the abbreviations instead of the names.
619 * @param bool|int $id - Optional id to return
624 * array reference of all State/Province abbreviations.
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
638 self
::$stateProvinceAbbreviation[$id] = CRM_Core_DAO
::singleValueQuery($query, $params);
640 return self
::$stateProvinceAbbreviation[$id];
643 $whereClause = FALSE;
646 $countryIsoCodes = self
::countryIsoCode();
647 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
649 foreach ($limitCodes as $code) {
650 $tmpArray = array_keys($countryIsoCodes, $code);
652 if (!empty($tmpArray)) {
653 $limitIds[] = array_shift($tmpArray);
656 if (!empty($limitIds)) {
657 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
660 self
::populate(self
::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
663 return self
::$stateProvinceAbbreviation;
667 * Get all the State/Province abbreviations from the database for the specified country.
669 * @param int $countryID
672 * array of all State/Province abbreviations for the given country.
674 public static function stateProvinceAbbreviationForCountry($countryID) {
675 if (!isset(\Civi
::$statics[__CLASS__
]['stateProvinceAbbreviationForCountry'][$countryID])) {
676 \Civi
::$statics[__CLASS__
]['stateProvinceAbbreviationForCountry'][$countryID] = [];
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];
683 * Get all the State/Province abbreviations from the database for the default country.
686 * array of all State/Province abbreviations for the given country.
688 public static function stateProvinceAbbreviationForDefaultCountry() {
689 return CRM_Core_PseudoConstant
::stateProvinceAbbreviationForCountry(Civi
::settings()->get('defaultContactCountry'));
693 * Get all the countries from database.
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.
699 * Note: any database errors will be trapped by the DAO.
702 * @param bool|int $id - Optional id to return
704 * @param bool $applyLimit
707 * array reference of all countries.
709 public static function country($id = FALSE, $applyLimit = TRUE) {
710 if (($id && empty(self
::$country[$id])) ||
!self
::$country ||
!$id) {
712 $config = CRM_Core_Config
::singleton();
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)) {
722 $config->countryLimit
=> 1,
726 $limitCodes = array_intersect(self
::countryIsoCode(), $limitCodes);
729 if (count($limitCodes)) {
730 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
736 self
::populate(self
::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
738 self
::$country = CRM_Core_BAO_Country
::_defaultContactCountries(self
::$country);
741 if (array_key_exists($id, self
::$country)) {
742 return self
::$country[$id];
748 return self
::$country;
752 * Get all the country ISO Code abbreviations from the database.
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.
758 * Note: any database errors will be trapped by the DAO.
764 * array reference of all country ISO codes.
766 public static function &countryIsoCode($id = FALSE) {
767 if (!self
::$countryIsoCode) {
768 self
::populate(self
::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
771 if (array_key_exists($id, self
::$countryIsoCode)) {
772 return self
::$countryIsoCode[$id];
775 return CRM_Core_DAO
::$_nullObject;
778 return self
::$countryIsoCode;
782 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
784 * Get all groups from database
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.
790 * Note: any database errors will be trapped by the DAO.
792 * @param string $groupType
793 * Type of group(Access/Mailing).
794 * @param bool $excludeHidden
795 * Exclude hidden groups.
799 * array reference of all groups.
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.
807 $condition = CRM_Contact_BAO_Group
::groupTypeCondition($groupType, $excludeHidden);
808 $groupKey = ($groupType ?
$groupType : 'null') . !empty($excludeHidden);
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);
813 return Civi
::$statics[__CLASS__
]['groups']['allGroup'][$groupKey];
817 * Get all permissioned groups from database.
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.
823 * Note: any database errors will be trapped by the DAO.
825 * @param string $groupType
826 * Type of group(Access/Mailing).
827 * @param bool $excludeHidden
828 * Exclude hidden groups.
832 * array reference of all groups.
834 public static function group($groupType = NULL, $excludeHidden = TRUE) {
835 return CRM_Core_Permission
::group($groupType, $excludeHidden);
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
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, ' ', TRUE);
851 * Get all permissioned groups from database.
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.
857 * Note: any database errors will be trapped by the DAO.
860 * @param bool $onlyPublic
861 * @param null $groupType
862 * @param bool $excludeHidden
865 * array reference of all groups.
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';
871 $condition .= " AND visibility != 'User and User Admin Only'";
875 $condition .= ' AND ' . CRM_Contact_BAO_Group
::groupTypeCondition($groupType);
878 if ($excludeHidden) {
879 $condition .= ' AND is_hidden != 1 ';
882 self
::populate(self
::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
885 return self
::$staticGroup;
889 * Get all Relationship Types from database.
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.
895 * Note: any database errors will be trapped by the DAO.
897 * @param string $valueColumnName
898 * Db column name/label.
900 * Reset relationship types if true.
901 * @param bool $isActive
902 * Filter by is_active. NULL to disable.
905 * array reference of all relationship types.
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] = [];
912 //now we have name/label columns CRM-3336
913 $column_a_b = "{$valueColumnName}_a_b";
914 $column_b_a = "{$valueColumnName}_b_a";
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;
922 $relationshipTypeDAO->find();
923 while ($relationshipTypeDAO->fetch()) {
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",
937 return self
::$relationshipType[$cacheKey];
941 * Name => Label pairs for all relationship types
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'];
954 return $relationshipTypes;
958 * Get all the ISO 4217 currency codes
960 * so far, we use this for validation only, so there's no point of putting this into the database
964 * array reference of all currency codes
966 public static function ¤cyCode() {
967 if (!self
::$currencyCode) {
969 $query = "SELECT name FROM civicrm_currency";
970 $dao = CRM_Core_DAO
::executeQuery($query);
972 while ($dao->fetch()) {
973 self
::$currencyCode[] = $dao->name
;
976 return self
::$currencyCode;
980 * Get all the County from database.
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.
986 * Note: any database errors will be trapped by the DAO.
989 * @param bool|int $id - Optional id to return
992 * array reference of all Counties
994 public static function &county($id = FALSE) {
995 if (!self
::$county) {
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');
1002 if (array_key_exists($id, self
::$county)) {
1003 return self
::$county[$id];
1006 return CRM_Core_DAO
::$_nullObject;
1009 return self
::$county;
1013 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1014 * Get all active payment processors
1016 * The static array paymentProcessor is returned
1020 * Get payment processors - default is to get only active ones.
1022 * Get test payment processors.
1024 * @param null $additionalCond
1027 * array of all payment processors
1029 public static function paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1030 $condition = "is_test = ";
1031 $condition .= ($test) ?
'1' : '0';
1033 if ($additionalCond) {
1034 $condition .= " AND ( $additionalCond ) ";
1037 // CRM-7178. Make sure we only include payment processors valid in this
1039 $condition .= " AND domain_id = " . CRM_Core_Config
::domainID();
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');
1046 return self
::$paymentProcessor[$cacheKey];
1050 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1052 * The static array paymentProcessorType is returned
1056 * Get payment processors - default is to get only active ones.
1059 * @param string $return
1062 * array of all payment processor types
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');
1069 if ($id && !empty(self
::$paymentProcessorType[$cacheKey][$id])) {
1070 return self
::$paymentProcessorType[$cacheKey][$id];
1072 return self
::$paymentProcessorType[$cacheKey];
1076 * Get all the World Regions from Database.
1082 * array reference of all World Regions
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');
1090 if (array_key_exists($id, self
::$worldRegions)) {
1091 return self
::$worldRegions[$id];
1094 return CRM_Core_DAO
::$_nullObject;
1098 return self
::$worldRegions;
1102 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1104 * Get all Activity Statuses.
1106 * The static array activityStatus is returned
1109 * @param string $column
1112 * array reference of all activity statuses
1114 public static function &activityStatus($column = 'label') {
1115 if (NULL === self
::$activityStatus) {
1116 self
::$activityStatus = [];
1118 if (!array_key_exists($column, self
::$activityStatus)) {
1119 self
::$activityStatus[$column] = [];
1121 self
::$activityStatus[$column] = CRM_Core_OptionGroup
::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1124 return self
::$activityStatus[$column];
1128 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1130 * Get all Visibility levels.
1132 * The static array visibility is returned
1135 * @param string $column
1138 * array reference of all Visibility levels.
1140 public static function &visibility($column = 'label') {
1141 if (!isset(self
::$visibility)) {
1142 self
::$visibility = [];
1145 if (!isset(self
::$visibility[$column])) {
1146 self
::$visibility[$column] = CRM_Core_OptionGroup
::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1149 return self
::$visibility[$column];
1153 * @param int $countryID
1154 * @param string $field
1158 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1159 static $_cache = NULL;
1161 $cacheKey = "{$countryID}_{$field}";
1166 if (!empty($_cache[$cacheKey])) {
1167 return $_cache[$cacheKey];
1171 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1172 FROM civicrm_state_province
1173 WHERE country_id = %1
1182 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1185 while ($dao->fetch()) {
1186 $result[$dao->id
] = $dao->name
;
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',
1197 $result = CRM_Utils_Array
::asort($result);
1200 $_cache[$cacheKey] = $result;
1202 CRM_Utils_Hook
::buildStateProvinceForCountry($countryID, $result);
1208 * @param int $stateID
1212 public static function &countyForState($stateID) {
1213 if (is_array($stateID)) {
1214 $states = implode(", ", $stateID);
1216 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
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";
1222 $dao = CRM_Core_DAO
::executeQuery($query);
1225 while ($dao->fetch()) {
1226 $result[$dao->id
] = $dao->abbreviation
. ': ' . $dao->name
;
1231 static $_cache = NULL;
1233 $cacheKey = "{$stateID}_name";
1238 if (!empty($_cache[$cacheKey])) {
1239 return $_cache[$cacheKey];
1243 SELECT civicrm_county.name name, civicrm_county.id id
1245 WHERE state_province_id = %1
1254 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1257 while ($dao->fetch()) {
1258 $result[$dao->id
] = $dao->name
;
1266 * Given a state ID return the country ID, this allows
1267 * us to populate forms and values for downstream code
1269 * @param int $stateID
1272 * the country id that the state belongs to
1274 public static function countryIDForStateID($stateID) {
1275 if (empty($stateID)) {
1281 FROM civicrm_state_province
1284 $params = [1 => [$stateID, 'Integer']];
1286 return CRM_Core_DAO
::singleValueQuery($query, $params);
1290 * Get all types of Greetings.
1292 * The static array of greeting is returned
1296 * Get All Email Greetings - default is to get only active ones.
1298 * @param string $columnName
1301 * array reference of all greetings.
1303 public static function greeting($filter, $columnName = 'label') {
1304 if (!isset(Civi
::$statics[__CLASS__
]['greeting'])) {
1305 Civi
::$statics[__CLASS__
]['greeting'] = [];
1308 $index = $filter['greeting_type'] . '_' . $columnName;
1310 // also add contactType to the array
1311 $contactType = $filter['contact_type'] ??
NULL;
1313 $index .= '_' . $contactType;
1316 if (empty(Civi
::$statics[__CLASS__
]['greeting'][$index])) {
1317 $filterCondition = NULL;
1319 $filterVal = 'v.filter =';
1320 switch ($contactType) {
1329 case 'Organization':
1333 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1336 Civi
::$statics[__CLASS__
]['greeting'][$index] = CRM_Core_OptionGroup
::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1339 return Civi
::$statics[__CLASS__
]['greeting'][$index];
1343 * Get all extensions.
1345 * The static array extensions
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.
1352 * array($fullyQualifiedName => $label) list of extensions
1354 public static function &getExtensions() {
1355 if (!self
::$extensions) {
1356 $compat = CRM_Extension_System
::getCompatibilityInfo();
1357 self
::$extensions = [];
1359 SELECT full_name, label
1360 FROM civicrm_extension
1363 $dao = CRM_Core_DAO
::executeQuery($sql);
1364 while ($dao->fetch()) {
1365 if (!empty($compat[$dao->full_name
]['force-uninstall'])) {
1368 self
::$extensions[$dao->full_name
] = $dao->label
;
1372 return self
::$extensions;
1376 * Get all options values.
1378 * The static array option values is returned
1381 * @param string $optionGroupName
1382 * Name of option group
1385 * @param string $condition
1386 * @param string $column
1387 * Whether to return 'name' or 'label'
1390 * array reference of all Option Values
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);
1398 return self
::$accountOptionValues[$cacheKey][$id] ??
NULL;
1401 return self
::$accountOptionValues[$cacheKey];
1405 * Fetch the list of active extensions of type 'module'
1407 * @param bool $fresh
1408 * Whether to forcibly reload extensions list from canonical store.
1411 * array(array('prefix' => $, 'file' => $))
1413 public static function getModuleExtensions($fresh = FALSE) {
1414 return CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles($fresh);
1418 * Get all tax rates.
1420 * The static array tax rates is returned
1423 * array list of tax rates with the financial type
1425 public static function getTaxRates() {
1426 if (!isset(Civi
::$statics[__CLASS__
]['taxRates'])) {
1427 Civi
::$statics[__CLASS__
]['taxRates'] = [];
1428 $option = civicrm_api3('option_value', 'get', [
1430 'option_group_id' => 'account_relationship',
1431 'name' => 'Sales Tax Account is',
1434 if ($option['count'] !== 0) {
1435 if ($option['count'] > 1) {
1436 foreach ($option['values'] as $opt) {
1437 $value[] = $opt['value'];
1441 $value[] = $option['values'][0]['value'];
1443 $where = 'AND efa.account_relationship IN (' . implode(', ', $value) . ' )';
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'
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
;
1461 return Civi
::$statics[__CLASS__
]['taxRates'];
1465 * Get participant status class options.
1469 public static function emailOnHoldOptions() {
1472 '1' => ts('On Hold Bounce'),
1473 '2' => ts('On Hold Opt Out'),
1478 * Render the field options from the available pseudoconstant.
1480 * Do not call this function directly or from untested code. Further cleanup is likely.
1482 * @param array $pseudoconstant
1483 * @param array $params
1484 * @param string|null $localizeContext
1485 * @param string $context
1487 * @return array|bool|mixed
1489 public static function renderOptionsFromTablePseudoconstant($pseudoconstant, &$params = [], $localizeContext = NULL, $context = '') {
1490 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($pseudoconstant['table']);
1491 if (!class_exists($daoName)) {
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());
1499 $select = 'SELECT %1 AS id, %2 AS label';
1502 $order = 'ORDER BY %2';
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'];
1510 elseif (in_array('name', $availableFields)) {
1511 $params[$nameField] = 'name';
1515 // Use abbrColum if context is abbreviate
1516 if ($context === 'abbreviate' && !empty($pseudoconstant['abbrColumn'])) {
1517 $params['labelColumn'] = $pseudoconstant['abbrColumn'];
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']);
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";
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';
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
],
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';
1546 // Support no sorting if $params[orderColumn] is FALSE
1547 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
1550 // Default to 'weight' if that column exists
1551 elseif (in_array('weight', $availableFields)) {
1552 $order = "ORDER BY weight";
1556 $query = "$select $from";
1558 $query .= " WHERE " . implode(' AND ', $wheres);
1560 $query .= ' ' . $order;
1561 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
1562 while ($dao->fetch()) {
1563 $output[$dao->id
] = $dao->label
;
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
1574 if ($localizeContext) {
1575 $I18nParams['context'] = $localizeContext;
1577 $i18n = CRM_Core_I18n
::singleton();
1578 $i18n->localizeArray($output, $I18nParams);
1580 // Maintain sort by label
1581 if ($order === 'ORDER BY %2') {
1582 $output = CRM_Utils_Array
::asort($output);