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']) ?
TRUE : FALSE;
189 // Merge params with defaults
192 'localize' => $localizeDefault,
193 'onlyActive' => ($context == 'validate' ||
$context == 'get') ?
FALSE : TRUE,
195 'context' => $context,
197 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getCanonicalClassName($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 // Ensure we have the canonical name for this field
215 $fieldName = CRM_Utils_Array
::value('name', $fieldSpec, $fieldName);
217 // Return false if field doesn't exist.
218 if (empty($fieldSpec)) {
222 elseif (!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' => CRM_Utils_Array
::value('condition', $pseudoconstant, []),
236 'keyColumn' => CRM_Utils_Array
::value('keyColumn', $pseudoconstant),
237 'labelColumn' => CRM_Utils_Array
::value('labelColumn', $pseudoconstant),
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 // Normalize params so the serialized cache string will be consistent.
268 CRM_Utils_Array
::remove($params, 'flip', 'fresh');
270 $cacheKey = $daoName . $fieldName . serialize($params);
272 // Retrieve cached options
273 if (isset(\Civi
::$statics[__CLASS__
][$cacheKey]) && empty($params['fresh'])) {
274 $output = \Civi
::$statics[__CLASS__
][$cacheKey];
277 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($pseudoconstant['table']);
278 if (!class_exists($daoName)) {
281 // Get list of fields for the option table
282 $dao = new $daoName();
283 $availableFields = array_keys($dao->fieldKeys());
285 $select = "SELECT %1 AS id, %2 AS label";
288 $order = "ORDER BY %2";
290 // Use machine name in certain contexts
291 if ($context == 'validate' ||
$context == 'match') {
292 $nameField = $context == 'validate' ?
'labelColumn' : 'keyColumn';
293 if (!empty($pseudoconstant['nameColumn'])) {
294 $params[$nameField] = $pseudoconstant['nameColumn'];
296 elseif (in_array('name', $availableFields)) {
297 $params[$nameField] = 'name';
301 // Use abbrColum if context is abbreviate
302 if ($context == 'abbreviate' && (in_array('abbreviation', $availableFields) ||
!empty($pseudoconstant['abbrColumn']))) {
303 $params['labelColumn'] = $pseudoconstant['abbrColumn'] ??
'abbreviation';
306 // Condition param can be passed as an sql clause string or an array of clauses
307 if (!empty($params['condition'])) {
308 $wheres[] = implode(' AND ', (array) $params['condition']);
310 // onlyActive param will automatically filter on common flags
311 if (!empty($params['onlyActive'])) {
312 foreach (['is_active' => 1, 'is_deleted' => 0, 'is_test' => 0, 'is_hidden' => 0] as $flag => $val) {
313 if (in_array($flag, $availableFields)) {
314 $wheres[] = "$flag = $val";
318 // Filter domain specific options
319 if (in_array('domain_id', $availableFields)) {
320 $wheres[] = 'domain_id = ' . CRM_Core_Config
::domainID();
323 1 => [$params['keyColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
],
324 2 => [$params['labelColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
],
325 3 => [$pseudoconstant['table'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
],
327 // Add orderColumn param
328 if (!empty($params['orderColumn'])) {
329 $queryParams[4] = [$params['orderColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
];
330 $order = "ORDER BY %4";
332 // Support no sorting if $params[orderColumn] is FALSE
333 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
336 // Default to 'weight' if that column exists
337 elseif (in_array('weight', $availableFields)) {
338 $order = "ORDER BY weight";
342 $query = "$select $from";
344 $query .= " WHERE " . implode($wheres, ' AND ');
346 $query .= ' ' . $order;
347 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
348 while ($dao->fetch()) {
349 $output[$dao->id
] = $dao->label
;
352 if (!empty($params['localize']) ||
$pseudoconstant['table'] == 'civicrm_country' ||
$pseudoconstant['table'] == 'civicrm_state_province') {
354 if (isset($fieldSpec['localize_context'])) {
355 $I18nParams['context'] = $fieldSpec['localize_context'];
357 $i18n = CRM_Core_I18n
::singleton();
358 $i18n->localizeArray($output, $I18nParams);
359 // Maintain sort by label
360 if ($order == "ORDER BY %2") {
361 $output = CRM_Utils_Array
::asort($output);
364 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $output, $params);
365 \Civi
::$statics[__CLASS__
][$cacheKey] = $output;
367 return $flip ?
array_flip($output) : $output;
371 // Return "Yes" and "No" for boolean fields
372 elseif (CRM_Utils_Array
::value('type', $fieldSpec) === CRM_Utils_Type
::T_BOOLEAN
) {
373 $output = $context == 'validate' ?
[0, 1] : CRM_Core_SelectValues
::boolean();
374 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $output, $params);
375 return $flip ?
array_flip($output) : $output;
377 // If we're still here, it's an error. Return FALSE.
382 * Fetch the translated label for a field given its key.
384 * @param string $baoName
385 * @param string $fieldName
386 * @param string|int $key
388 * TODO: Accept multivalued input?
390 * @return bool|null|string
391 * FALSE if the given field has no associated option list
392 * NULL if the given key has no corresponding option
393 * String if label is found
395 public static function getLabel($baoName, $fieldName, $key) {
396 $values = $baoName::buildOptions($fieldName, 'get');
397 if ($values === FALSE) {
400 return CRM_Utils_Array
::value($key, $values);
404 * Fetch the machine name for a field given its key.
406 * @param string $baoName
407 * @param string $fieldName
408 * @param string|int $key
410 * @return bool|null|string
411 * FALSE if the given field has no associated option list
412 * NULL if the given key has no corresponding option
413 * String if label is found
415 public static function getName($baoName, $fieldName, $key) {
416 $values = $baoName::buildOptions($fieldName, 'validate');
417 if ($values === FALSE) {
420 return CRM_Utils_Array
::value($key, $values);
424 * Fetch the key for a field option given its name.
426 * @param string $baoName
427 * @param string $fieldName
428 * @param string|int $value
430 * @return bool|null|string|int
431 * FALSE if the given field has no associated option list
432 * NULL if the given key has no corresponding option
433 * String|Number if key is found
435 public static function getKey($baoName, $fieldName, $value) {
436 $values = $baoName::buildOptions($fieldName, 'validate');
437 if ($values === FALSE) {
440 return CRM_Utils_Array
::key($value, $values);
444 * Lookup the admin page at which a field's option list can be edited
446 * @return string|null
448 public static function getOptionEditUrl($fieldSpec) {
449 // If it's an option group, that's easy
450 if (!empty($fieldSpec['pseudoconstant']['optionGroupName'])) {
451 return 'civicrm/admin/options/' . $fieldSpec['pseudoconstant']['optionGroupName'];
453 // For everything else...
454 elseif (!empty($fieldSpec['pseudoconstant']['table'])) {
455 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($fieldSpec['pseudoconstant']['table']);
459 // We don't have good mapping so have to do a bit of guesswork from the menu
460 list(, $parent, , $child) = explode('_', $daoName);
461 $sql = "SELECT path FROM civicrm_menu
462 WHERE page_callback LIKE '%CRM_Admin_Page_$child%' OR page_callback LIKE '%CRM_{$parent}_Page_$child%'
463 ORDER BY page_callback
465 return CRM_Core_DAO
::singleValueQuery($sql);
471 * @deprecated generic populate method.
472 * All pseudoconstant functions that use this method are also @deprecated
474 * The static array $var is populated from the db
475 * using the <b>$name DAO</b>.
477 * Note: any database errors will be trapped by the DAO.
480 * The associative array we will fill.
481 * @param string $name
482 * The name of the DAO.
484 * Get all objects. default is to get only active ones.
485 * @param string $retrieve
486 * The field that we are interested in (normally name, differs in some objects).
487 * @param string $filter
488 * The field that we want to filter the result set with.
489 * @param string $condition
490 * The condition that gets passed to the final query as the WHERE clause.
492 * @param bool $orderby
498 public static function populate(
503 $filter = 'is_active',
509 $cacheKey = CRM_Utils_Cache
::cleanKey("CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}");
510 $cache = CRM_Utils_Cache
::singleton();
511 $var = $cache->get($cacheKey);
512 if ($var !== NULL && empty($force)) {
516 /* @var CRM_Core_DAO $object */
517 $object = new $name();
519 $object->selectAdd();
520 $object->selectAdd("$key, $retrieve");
522 $object->whereAdd($condition);
526 $object->orderBy($retrieve);
529 $object->orderBy($orderby);
533 $object->$filter = 1;
534 $aclClauses = array_filter($name::getSelectWhereClause());
535 foreach ($aclClauses as $clause) {
536 $object->whereAdd($clause);
542 while ($object->fetch()) {
543 $var[$object->$key] = $object->$retrieve;
546 $cache->set($cacheKey, $var);
550 * Flush given pseudoconstant so it can be reread from db.
551 * nex time it's requested.
553 * @param bool|string $name pseudoconstant to be flushed
555 public static function flush($name = 'cache') {
556 if (isset(self
::$
$name)) {
559 if ($name == 'cache') {
560 CRM_Core_OptionGroup
::flushAll();
561 if (isset(\Civi
::$statics[__CLASS__
])) {
562 unset(\Civi
::$statics[__CLASS__
]);
568 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
570 * Get all Activty types.
572 * The static array activityType is returned
576 * array reference of all activity types.
578 public static function &activityType() {
579 $args = func_get_args();
580 $all = CRM_Utils_Array
::value(0, $args, TRUE);
581 $includeCaseActivities = CRM_Utils_Array
::value(1, $args, FALSE);
582 $reset = CRM_Utils_Array
::value(2, $args, FALSE);
583 $returnColumn = CRM_Utils_Array
::value(3, $args, 'label');
584 $includeCampaignActivities = CRM_Utils_Array
::value(4, $args, FALSE);
585 $onlyComponentActivities = CRM_Utils_Array
::value(5, $args, FALSE);
586 $index = (int) $all . '_' . $returnColumn . '_' . (int) $includeCaseActivities;
587 $index .= '_' . (int) $includeCampaignActivities;
588 $index .= '_' . (int) $onlyComponentActivities;
590 if (NULL === self
::$activityType) {
591 self
::$activityType = [];
594 if (!isset(self
::$activityType[$index]) ||
$reset) {
597 $condition = 'AND filter = 0';
599 $componentClause = " v.component_id IS NULL";
600 if ($onlyComponentActivities) {
601 $componentClause = " v.component_id IS NOT NULL";
605 $compInfo = CRM_Core_Component
::getEnabledComponents();
607 // build filter for listing activity types only if their
608 // respective components are enabled
609 foreach ($compInfo as $compName => $compObj) {
610 if ($compName == 'CiviCase') {
611 if ($includeCaseActivities) {
612 $componentIds[] = $compObj->componentID
;
615 elseif ($compName == 'CiviCampaign') {
616 if ($includeCampaignActivities) {
617 $componentIds[] = $compObj->componentID
;
621 $componentIds[] = $compObj->componentID
;
625 if (count($componentIds)) {
626 $componentIds = implode(',', $componentIds);
627 $componentClause = " ($componentClause OR v.component_id IN ($componentIds))";
628 if ($onlyComponentActivities) {
629 $componentClause = " ( v.component_id IN ($componentIds ) )";
632 $condition = $condition . ' AND ' . $componentClause;
634 self
::$activityType[$index] = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
636 return self
::$activityType[$index];
640 * Get all the State/Province from database.
642 * The static array stateProvince is returned, and if it's
643 * called the first time, the <b>State Province DAO</b> is used
644 * to get all the States.
646 * Note: any database errors will be trapped by the DAO.
649 * @param bool|int $id - Optional id to return
654 * array reference of all State/Provinces.
656 public static function &stateProvince($id = FALSE, $limit = TRUE) {
657 if (($id && empty(self
::$stateProvince[$id])) ||
!self
::$stateProvince ||
!$id) {
658 $whereClause = FALSE;
660 $countryIsoCodes = self
::countryIsoCode();
661 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
663 foreach ($limitCodes as $code) {
664 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
666 if (!empty($limitIds)) {
667 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
670 $whereClause = FALSE;
673 self
::populate(self
::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
675 // localise the province names if in an non-en_US locale
676 $tsLocale = CRM_Core_I18n
::getLocale();
677 if ($tsLocale != '' and $tsLocale != 'en_US') {
678 $i18n = CRM_Core_I18n
::singleton();
679 $i18n->localizeArray(self
::$stateProvince, [
680 'context' => 'province',
682 self
::$stateProvince = CRM_Utils_Array
::asort(self
::$stateProvince);
686 if (array_key_exists($id, self
::$stateProvince)) {
687 return self
::$stateProvince[$id];
694 return self
::$stateProvince;
698 * Get all the State/Province abbreviations from the database.
700 * Same as above, except gets the abbreviations instead of the names.
703 * @param bool|int $id - Optional id to return
708 * array reference of all State/Province abbreviations.
710 public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
711 if ($id && is_numeric($id)) {
712 if (!array_key_exists($id, (array) self
::$stateProvinceAbbreviation)) {
713 $query = "SELECT abbreviation
714 FROM civicrm_state_province
722 self
::$stateProvinceAbbreviation[$id] = CRM_Core_DAO
::singleValueQuery($query, $params);
724 return self
::$stateProvinceAbbreviation[$id];
727 $whereClause = FALSE;
730 $countryIsoCodes = self
::countryIsoCode();
731 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
733 foreach ($limitCodes as $code) {
734 $tmpArray = array_keys($countryIsoCodes, $code);
736 if (!empty($tmpArray)) {
737 $limitIds[] = array_shift($tmpArray);
740 if (!empty($limitIds)) {
741 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
744 self
::populate(self
::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
747 return self
::$stateProvinceAbbreviation;
751 * Get all the State/Province abbreviations from the database for the specified country.
753 * @param int $countryID
756 * array of all State/Province abbreviations for the given country.
758 public static function stateProvinceAbbreviationForCountry($countryID) {
759 if (!isset(\Civi
::$statics[__CLASS__
]['stateProvinceAbbreviationForCountry'][$countryID])) {
760 \Civi
::$statics[__CLASS__
]['stateProvinceAbbreviationForCountry'][$countryID] = [];
762 self
::populate(\Civi
::$statics[__CLASS__
]['stateProvinceAbbreviationForCountry'][$countryID], 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', "country_id = " . (int) $countryID, 'abbreviation');
763 return \Civi
::$statics[__CLASS__
]['stateProvinceAbbreviationForCountry'][$countryID];
767 * Get all the State/Province abbreviations from the database for the default country.
770 * array of all State/Province abbreviations for the given country.
772 public static function stateProvinceAbbreviationForDefaultCountry() {
773 return CRM_Core_PseudoConstant
::stateProvinceAbbreviationForCountry(Civi
::settings()->get('defaultContactCountry'));
777 * Get all the countries from database.
779 * The static array country is returned, and if it's
780 * called the first time, the <b>Country DAO</b> is used
781 * to get all the countries.
783 * Note: any database errors will be trapped by the DAO.
786 * @param bool|int $id - Optional id to return
788 * @param bool $applyLimit
791 * array reference of all countries.
793 public static function country($id = FALSE, $applyLimit = TRUE) {
794 if (($id && empty(self
::$country[$id])) ||
!self
::$country ||
!$id) {
796 $config = CRM_Core_Config
::singleton();
800 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
801 // (ensuring it's a subset of the legal values)
802 // K/P: We need to fix this, i dont think it works with new setting files
803 $limitCodes = CRM_Core_BAO_Country
::countryLimit();
804 if (!is_array($limitCodes)) {
806 $config->countryLimit
=> 1,
810 $limitCodes = array_intersect(self
::countryIsoCode(), $limitCodes);
813 if (count($limitCodes)) {
814 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
820 self
::populate(self
::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
822 // if default country is set, percolate it to the top
823 if (CRM_Core_BAO_Country
::defaultContactCountry()) {
824 $countryIsoCodes = self
::countryIsoCode();
825 $defaultID = array_search(CRM_Core_BAO_Country
::defaultContactCountry(), $countryIsoCodes);
826 if ($defaultID !== FALSE) {
827 $default[$defaultID] = CRM_Utils_Array
::value($defaultID, self
::$country);
828 self
::$country = $default + self
::$country;
832 // localise the country names if in an non-en_US locale
833 $tsLocale = CRM_Core_I18n
::getLocale();
834 if ($tsLocale != '' and $tsLocale != 'en_US') {
835 $i18n = CRM_Core_I18n
::singleton();
836 $i18n->localizeArray(self
::$country, [
837 'context' => 'country',
839 self
::$country = CRM_Utils_Array
::asort(self
::$country);
843 if (array_key_exists($id, self
::$country)) {
844 return self
::$country[$id];
850 return self
::$country;
854 * Get all the country ISO Code abbreviations from the database.
856 * The static array countryIsoCode is returned, and if it's
857 * called the first time, the <b>Country DAO</b> is used
858 * to get all the countries' ISO codes.
860 * Note: any database errors will be trapped by the DAO.
866 * array reference of all country ISO codes.
868 public static function &countryIsoCode($id = FALSE) {
869 if (!self
::$countryIsoCode) {
870 self
::populate(self
::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
873 if (array_key_exists($id, self
::$countryIsoCode)) {
874 return self
::$countryIsoCode[$id];
877 return CRM_Core_DAO
::$_nullObject;
880 return self
::$countryIsoCode;
884 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
886 * Get all groups from database
888 * The static array group is returned, and if it's
889 * called the first time, the <b>Group DAO</b> is used
890 * to get all the groups.
892 * Note: any database errors will be trapped by the DAO.
894 * @param string $groupType
895 * Type of group(Access/Mailing).
896 * @param bool $excludeHidden
897 * Exclude hidden groups.
901 * array reference of all groups.
903 public static function allGroup($groupType = NULL, $excludeHidden = TRUE) {
904 if ($groupType === 'validate') {
905 // validate gets passed through from getoptions. Handle in the deprecated
906 // fn rather than change the new pattern.
909 $condition = CRM_Contact_BAO_Group
::groupTypeCondition($groupType, $excludeHidden);
910 $groupKey = ($groupType ?
$groupType : 'null') . !empty($excludeHidden);
912 if (!isset(Civi
::$statics[__CLASS__
]['groups']['allGroup'][$groupKey])) {
913 self
::populate(Civi
::$statics[__CLASS__
]['groups']['allGroup'][$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
915 return Civi
::$statics[__CLASS__
]['groups']['allGroup'][$groupKey];
919 * Get all permissioned groups from database.
921 * The static array group is returned, and if it's
922 * called the first time, the <b>Group DAO</b> is used
923 * to get all the groups.
925 * Note: any database errors will be trapped by the DAO.
927 * @param string $groupType
928 * Type of group(Access/Mailing).
929 * @param bool $excludeHidden
930 * Exclude hidden groups.
934 * array reference of all groups.
936 public static function group($groupType = NULL, $excludeHidden = TRUE) {
937 return CRM_Core_Permission
::group($groupType, $excludeHidden);
941 * Fetch groups in a nested format suitable for use in select form element.
942 * @param bool $checkPermissions
943 * @param string|null $groupType
944 * @param bool $excludeHidden
947 public static function nestedGroup($checkPermissions = TRUE, $groupType = NULL, $excludeHidden = TRUE) {
948 $groups = $checkPermissions ? self
::group($groupType, $excludeHidden) : self
::allGroup($groupType, $excludeHidden);
949 return CRM_Contact_BAO_Group
::getGroupsHierarchy($groups, NULL, ' ', TRUE);
953 * Get all permissioned groups from database.
955 * The static array group is returned, and if it's
956 * called the first time, the <b>Group DAO</b> is used
957 * to get all the groups.
959 * Note: any database errors will be trapped by the DAO.
962 * @param bool $onlyPublic
963 * @param null $groupType
964 * @param bool $excludeHidden
967 * array reference of all groups.
969 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
970 if (!self
::$staticGroup) {
971 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
973 $condition .= " AND visibility != 'User and User Admin Only'";
977 $condition .= ' AND ' . CRM_Contact_BAO_Group
::groupTypeCondition($groupType);
980 if ($excludeHidden) {
981 $condition .= ' AND is_hidden != 1 ';
984 self
::populate(self
::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
987 return self
::$staticGroup;
991 * Get all Relationship Types from database.
993 * The static array group is returned, and if it's
994 * called the first time, the <b>RelationshipType DAO</b> is used
995 * to get all the relationship types.
997 * Note: any database errors will be trapped by the DAO.
999 * @param string $valueColumnName
1000 * Db column name/label.
1001 * @param bool $reset
1002 * Reset relationship types if true.
1003 * @param bool $isActive
1004 * Filter by is_active. NULL to disable.
1007 * array reference of all relationship types.
1009 public static function relationshipType($valueColumnName = 'label', $reset = FALSE, $isActive = 1) {
1010 $cacheKey = $valueColumnName . '::' . $isActive;
1011 if (!isset(self
::$relationshipType[$cacheKey]) ||
$reset) {
1012 self
::$relationshipType[$cacheKey] = [];
1014 //now we have name/label columns CRM-3336
1015 $column_a_b = "{$valueColumnName}_a_b";
1016 $column_b_a = "{$valueColumnName}_b_a";
1018 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1019 $relationshipTypeDAO->selectAdd();
1020 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1021 if ($isActive !== NULL) {
1022 $relationshipTypeDAO->is_active
= $isActive;
1024 $relationshipTypeDAO->find();
1025 while ($relationshipTypeDAO->fetch()) {
1027 self
::$relationshipType[$cacheKey][$relationshipTypeDAO->id
] = [
1028 'id' => $relationshipTypeDAO->id
,
1029 $column_a_b => $relationshipTypeDAO->$column_a_b,
1030 $column_b_a => $relationshipTypeDAO->$column_b_a,
1031 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1032 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1033 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1034 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1039 return self
::$relationshipType[$cacheKey];
1043 * Get all the ISO 4217 currency codes
1045 * so far, we use this for validation only, so there's no point of putting this into the database
1049 * array reference of all currency codes
1051 public static function ¤cyCode() {
1052 if (!self
::$currencyCode) {
1054 $query = "SELECT name FROM civicrm_currency";
1055 $dao = CRM_Core_DAO
::executeQuery($query);
1057 while ($dao->fetch()) {
1058 self
::$currencyCode[] = $dao->name
;
1061 return self
::$currencyCode;
1065 * Get all the County from database.
1067 * The static array county is returned, and if it's
1068 * called the first time, the <b>County DAO</b> is used
1069 * to get all the Counties.
1071 * Note: any database errors will be trapped by the DAO.
1074 * @param bool|int $id - Optional id to return
1077 * array reference of all Counties
1079 public static function &county($id = FALSE) {
1080 if (!self
::$county) {
1082 $config = CRM_Core_Config
::singleton();
1083 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1084 self
::populate(self
::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1087 if (array_key_exists($id, self
::$county)) {
1088 return self
::$county[$id];
1091 return CRM_Core_DAO
::$_nullObject;
1094 return self
::$county;
1098 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1099 * Get all active payment processors
1101 * The static array paymentProcessor is returned
1105 * Get payment processors - default is to get only active ones.
1107 * Get test payment processors.
1109 * @param null $additionalCond
1112 * array of all payment processors
1114 public static function paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1115 $condition = "is_test = ";
1116 $condition .= ($test) ?
'1' : '0';
1118 if ($additionalCond) {
1119 $condition .= " AND ( $additionalCond ) ";
1122 // CRM-7178. Make sure we only include payment processors valid in this
1124 $condition .= " AND domain_id = " . CRM_Core_Config
::domainID();
1126 $cacheKey = $condition . '_' . (int) $all;
1127 if (!isset(self
::$paymentProcessor[$cacheKey])) {
1128 self
::populate(self
::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1131 return self
::$paymentProcessor[$cacheKey];
1135 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1137 * The static array paymentProcessorType is returned
1141 * Get payment processors - default is to get only active ones.
1144 * @param string $return
1147 * array of all payment processor types
1149 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1150 $cacheKey = $id . '_' . $return;
1151 if (empty(self
::$paymentProcessorType[$cacheKey])) {
1152 self
::populate(self
::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1154 if ($id && !empty(self
::$paymentProcessorType[$cacheKey][$id])) {
1155 return self
::$paymentProcessorType[$cacheKey][$id];
1157 return self
::$paymentProcessorType[$cacheKey];
1161 * Get all the World Regions from Database.
1167 * array reference of all World Regions
1169 public static function &worldRegion($id = FALSE) {
1170 if (!self
::$worldRegions) {
1171 self
::populate(self
::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1175 if (array_key_exists($id, self
::$worldRegions)) {
1176 return self
::$worldRegions[$id];
1179 return CRM_Core_DAO
::$_nullObject;
1183 return self
::$worldRegions;
1187 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1189 * Get all Activity Statuses.
1191 * The static array activityStatus is returned
1194 * @param string $column
1197 * array reference of all activity statuses
1199 public static function &activityStatus($column = 'label') {
1200 if (NULL === self
::$activityStatus) {
1201 self
::$activityStatus = [];
1203 if (!array_key_exists($column, self
::$activityStatus)) {
1204 self
::$activityStatus[$column] = [];
1206 self
::$activityStatus[$column] = CRM_Core_OptionGroup
::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1209 return self
::$activityStatus[$column];
1213 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1215 * Get all Visibility levels.
1217 * The static array visibility is returned
1220 * @param string $column
1223 * array reference of all Visibility levels.
1225 public static function &visibility($column = 'label') {
1226 if (!isset(self
::$visibility)) {
1227 self
::$visibility = [];
1230 if (!isset(self
::$visibility[$column])) {
1231 self
::$visibility[$column] = CRM_Core_OptionGroup
::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1234 return self
::$visibility[$column];
1238 * @param int $countryID
1239 * @param string $field
1243 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1244 static $_cache = NULL;
1246 $cacheKey = "{$countryID}_{$field}";
1251 if (!empty($_cache[$cacheKey])) {
1252 return $_cache[$cacheKey];
1256 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1257 FROM civicrm_state_province
1258 WHERE country_id = %1
1267 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1270 while ($dao->fetch()) {
1271 $result[$dao->id
] = $dao->name
;
1274 // localise the stateProvince names if in an non-en_US locale
1275 $config = CRM_Core_Config
::singleton();
1276 $tsLocale = CRM_Core_I18n
::getLocale();
1277 if ($tsLocale != '' and $tsLocale != 'en_US') {
1278 $i18n = CRM_Core_I18n
::singleton();
1279 $i18n->localizeArray($result, [
1280 'context' => 'province',
1282 $result = CRM_Utils_Array
::asort($result);
1285 $_cache[$cacheKey] = $result;
1287 CRM_Utils_Hook
::buildStateProvinceForCountry($countryID, $result);
1293 * @param int $stateID
1297 public static function &countyForState($stateID) {
1298 if (is_array($stateID)) {
1299 $states = implode(", ", $stateID);
1301 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1303 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1304 WHERE civicrm_county.state_province_id in ( $states )
1305 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1307 $dao = CRM_Core_DAO
::executeQuery($query);
1310 while ($dao->fetch()) {
1311 $result[$dao->id
] = $dao->abbreviation
. ': ' . $dao->name
;
1316 static $_cache = NULL;
1318 $cacheKey = "{$stateID}_name";
1323 if (!empty($_cache[$cacheKey])) {
1324 return $_cache[$cacheKey];
1328 SELECT civicrm_county.name name, civicrm_county.id id
1330 WHERE state_province_id = %1
1339 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1342 while ($dao->fetch()) {
1343 $result[$dao->id
] = $dao->name
;
1351 * Given a state ID return the country ID, this allows
1352 * us to populate forms and values for downstream code
1354 * @param int $stateID
1357 * the country id that the state belongs to
1359 public static function countryIDForStateID($stateID) {
1360 if (empty($stateID)) {
1366 FROM civicrm_state_province
1369 $params = [1 => [$stateID, 'Integer']];
1371 return CRM_Core_DAO
::singleValueQuery($query, $params);
1375 * Get all types of Greetings.
1377 * The static array of greeting is returned
1381 * Get All Email Greetings - default is to get only active ones.
1383 * @param string $columnName
1386 * array reference of all greetings.
1388 public static function greeting($filter, $columnName = 'label') {
1389 if (!isset(Civi
::$statics[__CLASS__
]['greeting'])) {
1390 Civi
::$statics[__CLASS__
]['greeting'] = [];
1393 $index = $filter['greeting_type'] . '_' . $columnName;
1395 // also add contactType to the array
1396 $contactType = CRM_Utils_Array
::value('contact_type', $filter);
1398 $index .= '_' . $contactType;
1401 if (empty(Civi
::$statics[__CLASS__
]['greeting'][$index])) {
1402 $filterCondition = NULL;
1404 $filterVal = 'v.filter =';
1405 switch ($contactType) {
1414 case 'Organization':
1418 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1421 Civi
::$statics[__CLASS__
]['greeting'][$index] = CRM_Core_OptionGroup
::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1424 return Civi
::$statics[__CLASS__
]['greeting'][$index];
1428 * Get all extensions.
1430 * The static array extensions
1432 * FIXME: This is called by civix but not by any core code. We
1433 * should provide an API call which civix can use instead.
1437 * array($fullyQualifiedName => $label) list of extensions
1439 public static function &getExtensions() {
1440 if (!self
::$extensions) {
1441 $compat = CRM_Extension_System
::getCompatibilityInfo();
1442 self
::$extensions = [];
1444 SELECT full_name, label
1445 FROM civicrm_extension
1448 $dao = CRM_Core_DAO
::executeQuery($sql);
1449 while ($dao->fetch()) {
1450 if (!empty($compat[$dao->full_name
]['force-uninstall'])) {
1453 self
::$extensions[$dao->full_name
] = $dao->label
;
1457 return self
::$extensions;
1461 * Get all options values.
1463 * The static array option values is returned
1466 * @param bool $optionGroupName
1467 * Get All Option Group values- default is to get only active ones.
1470 * @param null $condition
1473 * array reference of all Option Group Name
1475 public static function accountOptionValues($optionGroupName, $id = NULL, $condition = NULL) {
1476 $cacheKey = $optionGroupName . '_' . $condition;
1477 if (empty(self
::$accountOptionValues[$cacheKey])) {
1478 self
::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup
::values($optionGroupName, FALSE, FALSE, FALSE, $condition);
1481 return CRM_Utils_Array
::value($id, self
::$accountOptionValues[$cacheKey]);
1484 return self
::$accountOptionValues[$cacheKey];
1488 * Fetch the list of active extensions of type 'module'
1490 * @param bool $fresh
1491 * Whether to forcibly reload extensions list from canonical store.
1494 * array(array('prefix' => $, 'file' => $))
1496 public static function getModuleExtensions($fresh = FALSE) {
1497 return CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles($fresh);
1501 * Get all tax rates.
1503 * The static array tax rates is returned
1506 * array list of tax rates with the financial type
1508 public static function getTaxRates() {
1509 if (!isset(Civi
::$statics[__CLASS__
]['taxRates'])) {
1510 Civi
::$statics[__CLASS__
]['taxRates'] = [];
1511 $option = civicrm_api3('option_value', 'get', [
1513 'option_group_id' => 'account_relationship',
1514 'name' => 'Sales Tax Account is',
1517 if ($option['count'] !== 0) {
1518 if ($option['count'] > 1) {
1519 foreach ($option['values'] as $opt) {
1520 $value[] = $opt['value'];
1524 $value[] = $option['values'][0]['value'];
1526 $where = 'AND efa.account_relationship IN (' . implode(', ', $value) . ' )';
1532 SELECT fa.tax_rate, efa.entity_id
1533 FROM civicrm_entity_financial_account efa
1534 INNER JOIN civicrm_financial_account fa ON fa.id = efa.financial_account_id
1535 WHERE efa.entity_table = 'civicrm_financial_type'
1537 AND fa.is_active = 1";
1538 $dao = CRM_Core_DAO
::executeQuery($sql);
1539 while ($dao->fetch()) {
1540 Civi
::$statics[__CLASS__
]['taxRates'][$dao->entity_id
] = $dao->tax_rate
;
1544 return Civi
::$statics[__CLASS__
]['taxRates'];
1548 * Get participant status class options.
1552 public static function emailOnHoldOptions() {
1555 '1' => ts('On Hold Bounce'),
1556 '2' => ts('On Hold Opt Out'),