3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
30 * Stores all constants and pseudo constants for CRM application.
32 * examples of constants are "Contact Type" which will always be either
33 * 'Individual', 'Household', 'Organization'.
35 * pseudo constants are entities from the database whose values rarely
36 * change. examples are list of countries, states, location types,
39 * currently we're getting the data from the underlying database. this
40 * will be reworked to use caching.
42 * Note: All pseudoconstants should be uninitialized or default to NULL.
43 * This provides greater consistency/predictability after flushing.
46 * @copyright CiviCRM LLC (c) 2004-2019
48 class CRM_Core_PseudoConstant
{
51 * Static cache for pseudoconstant arrays.
54 private static $cache;
59 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
61 private static $activityType;
67 private static $stateProvince;
73 private static $county;
76 * States/provinces abbreviations
79 private static $stateProvinceAbbreviation = [];
85 private static $country;
91 private static $countryIsoCode;
96 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
98 private static $group;
104 private static $relationshipType;
107 * Civicrm groups that are not smart groups
110 private static $staticGroup;
116 private static $currencyCode;
122 private static $paymentProcessor;
125 * Payment processor types
128 private static $paymentProcessorType;
134 private static $worldRegions;
139 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
141 private static $activityStatus;
147 private static $visibility;
153 private static $greeting;
156 * Extensions of type module
159 private static $extensions;
162 * Financial Account Type
165 private static $accountOptionValues;
168 * Low-level option getter, rarely accessed directly.
169 * NOTE: Rather than calling this function directly use CRM_*_BAO_*::buildOptions()
170 * @see https://docs.civicrm.org/dev/en/latest/framework/pseudoconstant/
172 * NOTE: If someone undertakes a refactoring of this, please consider the use-case of
173 * the Setting.getoptions API. There is no DAO/field, but it would be nice to use the
174 * same 'pseudoconstant' struct in *.settings.php. This means loosening the coupling
175 * between $field lookup and the $pseudoconstant evaluation.
177 * @param string $daoName
178 * @param string $fieldName
179 * @param array $params
180 * - name string name of the option group
181 * - flip boolean results are return in id => label format if false
182 * if true, the results are reversed
183 * - grouping boolean if true, return the value in 'grouping' column (currently unsupported for tables other than option_value)
184 * - localize boolean if true, localize the results before returning
185 * - condition string|array add condition(s) to the sql query - will be concatenated using 'AND'
186 * - keyColumn string the column to use for 'id'
187 * - labelColumn string the column to use for 'label'
188 * - orderColumn string the column to use for sorting, defaults to 'weight' column if one exists, else defaults to labelColumn
189 * - onlyActive boolean return only the action option values
190 * - fresh boolean ignore cache entries and go back to DB
191 * @param string $context : Context string
192 * @see CRM_Core_DAO::buildOptionsContext
195 * array on success, FALSE on error.
198 public static function get($daoName, $fieldName, $params = [], $context = NULL) {
199 CRM_Core_DAO
::buildOptionsContext($context);
200 $flip = !empty($params['flip']);
201 // Historically this was 'false' but according to the notes in
202 // CRM_Core_DAO::buildOptionsContext it should be context dependent.
203 // timidly changing for 'search' only to fix world_region in search options.
204 $localizeDefault = in_array($context, ['search']) ?
TRUE : FALSE;
205 // Merge params with defaults
208 'localize' => $localizeDefault,
209 'onlyActive' => ($context == 'validate' ||
$context == 'get') ?
FALSE : TRUE,
211 'context' => $context,
213 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getCanonicalClassName($daoName));
215 // Custom fields are not in the schema
216 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
217 $customField = new CRM_Core_BAO_CustomField();
218 $customField->id
= (int) substr($fieldName, 7);
219 $options = $customField->getOptions($context);
220 if ($options && $flip) {
221 $options = array_flip($options);
226 // Core field: load schema
227 $dao = new $daoName();
228 $fieldSpec = $dao->getFieldSpec($fieldName);
230 // Ensure we have the canonical name for this field
231 $fieldName = CRM_Utils_Array
::value('name', $fieldSpec, $fieldName);
233 // Return false if field doesn't exist.
234 if (empty($fieldSpec)) {
238 elseif (!empty($fieldSpec['pseudoconstant'])) {
239 $pseudoconstant = $fieldSpec['pseudoconstant'];
241 // if callback is specified..
242 if (!empty($pseudoconstant['callback'])) {
243 $fieldOptions = call_user_func(Civi\Core\Resolver
::singleton()->get($pseudoconstant['callback']), $context);
244 //CRM-18223: Allow additions to field options via hook.
245 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $fieldOptions, $params);
246 return $fieldOptions;
249 // Merge params with schema defaults
251 'condition' => CRM_Utils_Array
::value('condition', $pseudoconstant, []),
252 'keyColumn' => CRM_Utils_Array
::value('keyColumn', $pseudoconstant),
253 'labelColumn' => CRM_Utils_Array
::value('labelColumn', $pseudoconstant),
256 if ($context == 'abbreviate') {
257 switch ($fieldName) {
258 case 'state_province_id':
259 $params['labelColumn'] = 'abbreviation';
263 $params['labelColumn'] = 'iso_code';
270 // Fetch option group from option_value table
271 if (!empty($pseudoconstant['optionGroupName'])) {
272 if ($context == 'validate') {
273 $params['labelColumn'] = 'name';
275 if ($context == 'match') {
276 $params['keyColumn'] = 'name';
278 // Call our generic fn for retrieving from the option_value table
279 $options = CRM_Core_OptionGroup
::values(
280 $pseudoconstant['optionGroupName'],
284 $params['condition'] ?
' AND ' . implode(' AND ', (array) $params['condition']) : NULL,
285 $params['labelColumn'] ?
$params['labelColumn'] : 'label',
286 $params['onlyActive'],
288 $params['keyColumn'] ?
$params['keyColumn'] : 'value',
289 !empty($params['orderColumn']) ?
$params['orderColumn'] : 'weight'
291 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $options, $params);
295 // Fetch options from other tables
296 if (!empty($pseudoconstant['table'])) {
297 // Normalize params so the serialized cache string will be consistent.
298 CRM_Utils_Array
::remove($params, 'flip', 'fresh');
300 $cacheKey = $daoName . $fieldName . serialize($params);
302 // Retrieve cached options
303 if (isset(self
::$cache[$cacheKey]) && empty($params['fresh'])) {
304 $output = self
::$cache[$cacheKey];
307 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($pseudoconstant['table']);
308 if (!class_exists($daoName)) {
311 // Get list of fields for the option table
312 $dao = new $daoName();
313 $availableFields = array_keys($dao->fieldKeys());
315 $select = "SELECT %1 AS id, %2 AS label";
318 $order = "ORDER BY %2";
320 // Use machine name in certain contexts
321 if ($context == 'validate' ||
$context == 'match') {
322 $nameField = $context == 'validate' ?
'labelColumn' : 'keyColumn';
323 if (!empty($pseudoconstant['nameColumn'])) {
324 $params[$nameField] = $pseudoconstant['nameColumn'];
326 elseif (in_array('name', $availableFields)) {
327 $params[$nameField] = 'name';
330 // Condition param can be passed as an sql clause string or an array of clauses
331 if (!empty($params['condition'])) {
332 $wheres[] = implode(' AND ', (array) $params['condition']);
334 // onlyActive param will automatically filter on common flags
335 if (!empty($params['onlyActive'])) {
336 foreach (['is_active' => 1, 'is_deleted' => 0, 'is_test' => 0, 'is_hidden' => 0] as $flag => $val) {
337 if (in_array($flag, $availableFields)) {
338 $wheres[] = "$flag = $val";
342 // Filter domain specific options
343 if (in_array('domain_id', $availableFields)) {
344 $wheres[] = 'domain_id = ' . CRM_Core_Config
::domainID();
347 1 => [$params['keyColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
],
348 2 => [$params['labelColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
],
349 3 => [$pseudoconstant['table'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
],
351 // Add orderColumn param
352 if (!empty($params['orderColumn'])) {
353 $queryParams[4] = [$params['orderColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
];
354 $order = "ORDER BY %4";
356 // Support no sorting if $params[orderColumn] is FALSE
357 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
360 // Default to 'weight' if that column exists
361 elseif (in_array('weight', $availableFields)) {
362 $order = "ORDER BY weight";
366 $query = "$select $from";
368 $query .= " WHERE " . implode($wheres, ' AND ');
370 $query .= ' ' . $order;
371 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
372 while ($dao->fetch()) {
373 $output[$dao->id
] = $dao->label
;
376 if (!empty($params['localize']) ||
$pseudoconstant['table'] == 'civicrm_country' ||
$pseudoconstant['table'] == 'civicrm_state_province') {
378 if (isset($fieldSpec['localize_context'])) {
379 $I18nParams['context'] = $fieldSpec['localize_context'];
381 $i18n = CRM_Core_I18n
::singleton();
382 $i18n->localizeArray($output, $I18nParams);
383 // Maintain sort by label
384 if ($order == "ORDER BY %2") {
385 CRM_Utils_Array
::asort($output);
388 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $output, $params);
389 self
::$cache[$cacheKey] = $output;
391 return $flip ?
array_flip($output) : $output;
395 // Return "Yes" and "No" for boolean fields
396 elseif (CRM_Utils_Array
::value('type', $fieldSpec) === CRM_Utils_Type
::T_BOOLEAN
) {
397 $output = $context == 'validate' ?
[0, 1] : CRM_Core_SelectValues
::boolean();
398 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $output, $params);
399 return $flip ?
array_flip($output) : $output;
401 // If we're still here, it's an error. Return FALSE.
406 * Fetch the translated label for a field given its key.
408 * @param string $baoName
409 * @param string $fieldName
410 * @param string|int $key
412 * TODO: Accept multivalued input?
414 * @return bool|null|string
415 * FALSE if the given field has no associated option list
416 * NULL if the given key has no corresponding option
417 * String if label is found
419 public static function getLabel($baoName, $fieldName, $key) {
420 $values = $baoName::buildOptions($fieldName, 'get');
421 if ($values === FALSE) {
424 return CRM_Utils_Array
::value($key, $values);
428 * Fetch the machine name for a field given its key.
430 * @param string $baoName
431 * @param string $fieldName
432 * @param string|int $key
434 * @return bool|null|string
435 * FALSE if the given field has no associated option list
436 * NULL if the given key has no corresponding option
437 * String if label is found
439 public static function getName($baoName, $fieldName, $key) {
440 $values = $baoName::buildOptions($fieldName, 'validate');
441 if ($values === FALSE) {
444 return CRM_Utils_Array
::value($key, $values);
448 * Fetch the key for a field option given its name.
450 * @param string $baoName
451 * @param string $fieldName
452 * @param string|int $value
454 * @return bool|null|string|int
455 * FALSE if the given field has no associated option list
456 * NULL if the given key has no corresponding option
457 * String|Number if key is found
459 public static function getKey($baoName, $fieldName, $value) {
460 $values = $baoName::buildOptions($fieldName, 'validate');
461 if ($values === FALSE) {
464 return CRM_Utils_Array
::key($value, $values);
468 * Lookup the admin page at which a field's option list can be edited
470 * @return string|null
472 public static function getOptionEditUrl($fieldSpec) {
473 // If it's an option group, that's easy
474 if (!empty($fieldSpec['pseudoconstant']['optionGroupName'])) {
475 return 'civicrm/admin/options/' . $fieldSpec['pseudoconstant']['optionGroupName'];
477 // For everything else...
478 elseif (!empty($fieldSpec['pseudoconstant']['table'])) {
479 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($fieldSpec['pseudoconstant']['table']);
483 // We don't have good mapping so have to do a bit of guesswork from the menu
484 list(, $parent, , $child) = explode('_', $daoName);
485 $sql = "SELECT path FROM civicrm_menu
486 WHERE page_callback LIKE '%CRM_Admin_Page_$child%' OR page_callback LIKE '%CRM_{$parent}_Page_$child%'
487 ORDER BY page_callback
489 return CRM_Core_Dao
::singleValueQuery($sql);
495 * @deprecated generic populate method.
496 * All pseudoconstant functions that use this method are also @deprecated
498 * The static array $var is populated from the db
499 * using the <b>$name DAO</b>.
501 * Note: any database errors will be trapped by the DAO.
504 * The associative array we will fill.
505 * @param string $name
506 * The name of the DAO.
508 * Get all objects. default is to get only active ones.
509 * @param string $retrieve
510 * The field that we are interested in (normally name, differs in some objects).
511 * @param string $filter
512 * The field that we want to filter the result set with.
513 * @param string $condition
514 * The condition that gets passed to the final query as the WHERE clause.
516 * @param bool $orderby
522 public static function populate(
527 $filter = 'is_active',
533 $cacheKey = CRM_Core_BAO_Cache
::cleanKey("CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}");
534 $cache = CRM_Utils_Cache
::singleton();
535 $var = $cache->get($cacheKey);
536 if ($var !== NULL && empty($force)) {
540 /* @var CRM_Core_DAO $object */
541 $object = new $name();
543 $object->selectAdd();
544 $object->selectAdd("$key, $retrieve");
546 $object->whereAdd($condition);
550 $object->orderBy($retrieve);
553 $object->orderBy($orderby);
557 $object->$filter = 1;
558 $aclClauses = array_filter($name::getSelectWhereClause());
559 foreach ($aclClauses as $clause) {
560 $object->whereAdd($clause);
566 while ($object->fetch()) {
567 $var[$object->$key] = $object->$retrieve;
570 $cache->set($cacheKey, $var);
574 * Flush given pseudoconstant so it can be reread from db.
575 * nex time it's requested.
577 * @param bool|string $name pseudoconstant to be flushed
579 public static function flush($name = 'cache') {
580 if (isset(self
::$
$name)) {
583 if ($name == 'cache') {
584 CRM_Core_OptionGroup
::flushAll();
585 if (isset(\Civi
::$statics[__CLASS__
])) {
586 unset(\Civi
::$statics[__CLASS__
]);
592 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
594 * Get all Activty types.
596 * The static array activityType is returned
600 * array reference of all activity types.
602 public static function &activityType() {
603 $args = func_get_args();
604 $all = CRM_Utils_Array
::value(0, $args, TRUE);
605 $includeCaseActivities = CRM_Utils_Array
::value(1, $args, FALSE);
606 $reset = CRM_Utils_Array
::value(2, $args, FALSE);
607 $returnColumn = CRM_Utils_Array
::value(3, $args, 'label');
608 $includeCampaignActivities = CRM_Utils_Array
::value(4, $args, FALSE);
609 $onlyComponentActivities = CRM_Utils_Array
::value(5, $args, FALSE);
610 $index = (int) $all . '_' . $returnColumn . '_' . (int) $includeCaseActivities;
611 $index .= '_' . (int) $includeCampaignActivities;
612 $index .= '_' . (int) $onlyComponentActivities;
614 if (NULL === self
::$activityType) {
615 self
::$activityType = [];
618 if (!isset(self
::$activityType[$index]) ||
$reset) {
621 $condition = 'AND filter = 0';
623 $componentClause = " v.component_id IS NULL";
624 if ($onlyComponentActivities) {
625 $componentClause = " v.component_id IS NOT NULL";
629 $compInfo = CRM_Core_Component
::getEnabledComponents();
631 // build filter for listing activity types only if their
632 // respective components are enabled
633 foreach ($compInfo as $compName => $compObj) {
634 if ($compName == 'CiviCase') {
635 if ($includeCaseActivities) {
636 $componentIds[] = $compObj->componentID
;
639 elseif ($compName == 'CiviCampaign') {
640 if ($includeCampaignActivities) {
641 $componentIds[] = $compObj->componentID
;
645 $componentIds[] = $compObj->componentID
;
649 if (count($componentIds)) {
650 $componentIds = implode(',', $componentIds);
651 $componentClause = " ($componentClause OR v.component_id IN ($componentIds))";
652 if ($onlyComponentActivities) {
653 $componentClause = " ( v.component_id IN ($componentIds ) )";
656 $condition = $condition . ' AND ' . $componentClause;
658 self
::$activityType[$index] = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
660 return self
::$activityType[$index];
664 * Get all the State/Province from database.
666 * The static array stateProvince is returned, and if it's
667 * called the first time, the <b>State Province DAO</b> is used
668 * to get all the States.
670 * Note: any database errors will be trapped by the DAO.
673 * @param bool|int $id - Optional id to return
678 * array reference of all State/Provinces.
680 public static function &stateProvince($id = FALSE, $limit = TRUE) {
681 if (($id && !CRM_Utils_Array
::value($id, self
::$stateProvince)) ||
!self
::$stateProvince ||
!$id) {
682 $whereClause = FALSE;
684 $countryIsoCodes = self
::countryIsoCode();
685 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
687 foreach ($limitCodes as $code) {
688 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
690 if (!empty($limitIds)) {
691 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
694 $whereClause = FALSE;
697 self
::populate(self
::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
699 // localise the province names if in an non-en_US locale
700 $tsLocale = CRM_Core_I18n
::getLocale();
701 if ($tsLocale != '' and $tsLocale != 'en_US') {
702 $i18n = CRM_Core_I18n
::singleton();
703 $i18n->localizeArray(self
::$stateProvince, [
704 'context' => 'province',
706 self
::$stateProvince = CRM_Utils_Array
::asort(self
::$stateProvince);
710 if (array_key_exists($id, self
::$stateProvince)) {
711 return self
::$stateProvince[$id];
718 return self
::$stateProvince;
722 * Get all the State/Province abbreviations from the database.
724 * Same as above, except gets the abbreviations instead of the names.
727 * @param bool|int $id - Optional id to return
732 * array reference of all State/Province abbreviations.
734 public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
735 if ($id && is_numeric($id)) {
736 if (!array_key_exists($id, (array) self
::$stateProvinceAbbreviation)) {
737 $query = "SELECT abbreviation
738 FROM civicrm_state_province
746 self
::$stateProvinceAbbreviation[$id] = CRM_Core_DAO
::singleValueQuery($query, $params);
748 return self
::$stateProvinceAbbreviation[$id];
751 $whereClause = FALSE;
754 $countryIsoCodes = self
::countryIsoCode();
755 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
757 foreach ($limitCodes as $code) {
758 $tmpArray = array_keys($countryIsoCodes, $code);
760 if (!empty($tmpArray)) {
761 $limitIds[] = array_shift($tmpArray);
764 if (!empty($limitIds)) {
765 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
768 self
::populate(self
::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
771 return self
::$stateProvinceAbbreviation;
775 * Get all the State/Province abbreviations from the database for the specified country.
777 * @param int $countryID
780 * array of all State/Province abbreviations for the given country.
782 public static function stateProvinceAbbreviationForCountry($countryID) {
783 if (!isset(\Civi
::$statics[__CLASS__
]['stateProvinceAbbreviationForCountry'][$countryID])) {
784 \Civi
::$statics[__CLASS__
]['stateProvinceAbbreviationForCountry'][$countryID] = [];
786 self
::populate(\Civi
::$statics[__CLASS__
]['stateProvinceAbbreviationForCountry'][$countryID], 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', "country_id = " . (int) $countryID, 'abbreviation');
787 return \Civi
::$statics[__CLASS__
]['stateProvinceAbbreviationForCountry'][$countryID];
791 * Get all the State/Province abbreviations from the database for the default country.
794 * array of all State/Province abbreviations for the given country.
796 public static function stateProvinceAbbreviationForDefaultCountry() {
797 return CRM_Core_PseudoConstant
::stateProvinceAbbreviationForCountry(Civi
::settings()->get('defaultContactCountry'));
801 * Get all the countries from database.
803 * The static array country is returned, and if it's
804 * called the first time, the <b>Country DAO</b> is used
805 * to get all the countries.
807 * Note: any database errors will be trapped by the DAO.
810 * @param bool|int $id - Optional id to return
812 * @param bool $applyLimit
815 * array reference of all countries.
817 public static function country($id = FALSE, $applyLimit = TRUE) {
818 if (($id && !CRM_Utils_Array
::value($id, self
::$country)) ||
!self
::$country ||
!$id) {
820 $config = CRM_Core_Config
::singleton();
824 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
825 // (ensuring it's a subset of the legal values)
826 // K/P: We need to fix this, i dont think it works with new setting files
827 $limitCodes = CRM_Core_BAO_Country
::countryLimit();
828 if (!is_array($limitCodes)) {
830 $config->countryLimit
=> 1,
834 $limitCodes = array_intersect(self
::countryIsoCode(), $limitCodes);
837 if (count($limitCodes)) {
838 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
844 self
::populate(self
::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
846 // if default country is set, percolate it to the top
847 if ($config->defaultContactCountry()) {
848 $countryIsoCodes = self
::countryIsoCode();
849 $defaultID = array_search($config->defaultContactCountry(), $countryIsoCodes);
850 if ($defaultID !== FALSE) {
851 $default[$defaultID] = CRM_Utils_Array
::value($defaultID, self
::$country);
852 self
::$country = $default + self
::$country;
856 // localise the country names if in an non-en_US locale
857 $tsLocale = CRM_Core_I18n
::getLocale();
858 if ($tsLocale != '' and $tsLocale != 'en_US') {
859 $i18n = CRM_Core_I18n
::singleton();
860 $i18n->localizeArray(self
::$country, [
861 'context' => 'country',
863 self
::$country = CRM_Utils_Array
::asort(self
::$country);
867 if (array_key_exists($id, self
::$country)) {
868 return self
::$country[$id];
874 return self
::$country;
878 * Get all the country ISO Code abbreviations from the database.
880 * The static array countryIsoCode is returned, and if it's
881 * called the first time, the <b>Country DAO</b> is used
882 * to get all the countries' ISO codes.
884 * Note: any database errors will be trapped by the DAO.
890 * array reference of all country ISO codes.
892 public static function &countryIsoCode($id = FALSE) {
893 if (!self
::$countryIsoCode) {
894 self
::populate(self
::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
897 if (array_key_exists($id, self
::$countryIsoCode)) {
898 return self
::$countryIsoCode[$id];
901 return CRM_Core_DAO
::$_nullObject;
904 return self
::$countryIsoCode;
908 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
910 * Get all groups from database
912 * The static array group is returned, and if it's
913 * called the first time, the <b>Group DAO</b> is used
914 * to get all the groups.
916 * Note: any database errors will be trapped by the DAO.
918 * @param string $groupType
919 * Type of group(Access/Mailing).
920 * @param bool $excludeHidden
921 * Exclude hidden groups.
925 * array reference of all groups.
927 public static function allGroup($groupType = NULL, $excludeHidden = TRUE) {
928 if ($groupType === 'validate') {
929 // validate gets passed through from getoptions. Handle in the deprecated
930 // fn rather than change the new pattern.
933 $condition = CRM_Contact_BAO_Group
::groupTypeCondition($groupType, $excludeHidden);
934 $groupKey = ($groupType ?
$groupType : 'null') . !empty($excludeHidden);
936 if (!isset(Civi
::$statics[__CLASS__
]['groups']['allGroup'][$groupKey])) {
937 self
::populate(Civi
::$statics[__CLASS__
]['groups']['allGroup'][$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
939 return Civi
::$statics[__CLASS__
]['groups']['allGroup'][$groupKey];
943 * Get all permissioned groups from database.
945 * The static array group is returned, and if it's
946 * called the first time, the <b>Group DAO</b> is used
947 * to get all the groups.
949 * Note: any database errors will be trapped by the DAO.
951 * @param string $groupType
952 * Type of group(Access/Mailing).
953 * @param bool $excludeHidden
954 * Exclude hidden groups.
958 * array reference of all groups.
960 public static function group($groupType = NULL, $excludeHidden = TRUE) {
961 return CRM_Core_Permission
::group($groupType, $excludeHidden);
965 * Fetch groups in a nested format suitable for use in select form element.
966 * @param bool $checkPermissions
967 * @param string|null $groupType
968 * @param bool $excludeHidden
971 public static function nestedGroup($checkPermissions = TRUE, $groupType = NULL, $excludeHidden = TRUE) {
972 $groups = $checkPermissions ? self
::group($groupType, $excludeHidden) : self
::allGroup($groupType, $excludeHidden);
973 return CRM_Contact_BAO_Group
::getGroupsHierarchy($groups, NULL, ' ', TRUE);
977 * Get all permissioned groups from database.
979 * The static array group is returned, and if it's
980 * called the first time, the <b>Group DAO</b> is used
981 * to get all the groups.
983 * Note: any database errors will be trapped by the DAO.
986 * @param bool $onlyPublic
987 * @param null $groupType
988 * @param bool $excludeHidden
991 * array reference of all groups.
993 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
994 if (!self
::$staticGroup) {
995 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
997 $condition .= " AND visibility != 'User and User Admin Only'";
1001 $condition .= ' AND ' . CRM_Contact_BAO_Group
::groupTypeCondition($groupType);
1004 if ($excludeHidden) {
1005 $condition .= ' AND is_hidden != 1 ';
1008 self
::populate(self
::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
1011 return self
::$staticGroup;
1015 * Get all Relationship Types from database.
1017 * The static array group is returned, and if it's
1018 * called the first time, the <b>RelationshipType DAO</b> is used
1019 * to get all the relationship types.
1021 * Note: any database errors will be trapped by the DAO.
1023 * @param string $valueColumnName
1024 * Db column name/label.
1025 * @param bool $reset
1026 * Reset relationship types if true.
1027 * @param bool $isActive
1028 * Filter by is_active. NULL to disable.
1031 * array reference of all relationship types.
1033 public static function &relationshipType($valueColumnName = 'label', $reset = FALSE, $isActive = 1) {
1034 $cacheKey = $valueColumnName . '::' . $isActive;
1035 if (!CRM_Utils_Array
::value($cacheKey, self
::$relationshipType) ||
$reset) {
1036 self
::$relationshipType[$cacheKey] = [];
1038 //now we have name/label columns CRM-3336
1039 $column_a_b = "{$valueColumnName}_a_b";
1040 $column_b_a = "{$valueColumnName}_b_a";
1042 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1043 $relationshipTypeDAO->selectAdd();
1044 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1045 if ($isActive !== NULL) {
1046 $relationshipTypeDAO->is_active
= $isActive;
1048 $relationshipTypeDAO->find();
1049 while ($relationshipTypeDAO->fetch()) {
1051 self
::$relationshipType[$cacheKey][$relationshipTypeDAO->id
] = [
1052 'id' => $relationshipTypeDAO->id
,
1053 $column_a_b => $relationshipTypeDAO->$column_a_b,
1054 $column_b_a => $relationshipTypeDAO->$column_b_a,
1055 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1056 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1057 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1058 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1063 return self
::$relationshipType[$cacheKey];
1067 * Get all the ISO 4217 currency codes
1069 * so far, we use this for validation only, so there's no point of putting this into the database
1073 * array reference of all currency codes
1075 public static function ¤cyCode() {
1076 if (!self
::$currencyCode) {
1078 $query = "SELECT name FROM civicrm_currency";
1079 $dao = CRM_Core_DAO
::executeQuery($query);
1081 while ($dao->fetch()) {
1082 self
::$currencyCode[] = $dao->name
;
1085 return self
::$currencyCode;
1089 * Get all the County from database.
1091 * The static array county is returned, and if it's
1092 * called the first time, the <b>County DAO</b> is used
1093 * to get all the Counties.
1095 * Note: any database errors will be trapped by the DAO.
1098 * @param bool|int $id - Optional id to return
1101 * array reference of all Counties
1103 public static function &county($id = FALSE) {
1104 if (!self
::$county) {
1106 $config = CRM_Core_Config
::singleton();
1107 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1108 self
::populate(self
::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1111 if (array_key_exists($id, self
::$county)) {
1112 return self
::$county[$id];
1115 return CRM_Core_DAO
::$_nullObject;
1118 return self
::$county;
1122 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1123 * Get all active payment processors
1125 * The static array paymentProcessor is returned
1129 * Get payment processors - default is to get only active ones.
1131 * Get test payment processors.
1133 * @param null $additionalCond
1136 * array of all payment processors
1138 public static function paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1139 $condition = "is_test = ";
1140 $condition .= ($test) ?
'1' : '0';
1142 if ($additionalCond) {
1143 $condition .= " AND ( $additionalCond ) ";
1146 // CRM-7178. Make sure we only include payment processors valid in this
1148 $condition .= " AND domain_id = " . CRM_Core_Config
::domainID();
1150 $cacheKey = $condition . '_' . (int) $all;
1151 if (!isset(self
::$paymentProcessor[$cacheKey])) {
1152 self
::populate(self
::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1155 return self
::$paymentProcessor[$cacheKey];
1159 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1161 * The static array paymentProcessorType is returned
1165 * Get payment processors - default is to get only active ones.
1168 * @param string $return
1171 * array of all payment processor types
1173 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1174 $cacheKey = $id . '_' . $return;
1175 if (empty(self
::$paymentProcessorType[$cacheKey])) {
1176 self
::populate(self
::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1178 if ($id && CRM_Utils_Array
::value($id, self
::$paymentProcessorType[$cacheKey])) {
1179 return self
::$paymentProcessorType[$cacheKey][$id];
1181 return self
::$paymentProcessorType[$cacheKey];
1185 * Get all the World Regions from Database.
1191 * array reference of all World Regions
1193 public static function &worldRegion($id = FALSE) {
1194 if (!self
::$worldRegions) {
1195 self
::populate(self
::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1199 if (array_key_exists($id, self
::$worldRegions)) {
1200 return self
::$worldRegions[$id];
1203 return CRM_Core_DAO
::$_nullObject;
1207 return self
::$worldRegions;
1211 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1213 * Get all Activity Statuses.
1215 * The static array activityStatus is returned
1218 * @param string $column
1221 * array reference of all activity statuses
1223 public static function &activityStatus($column = 'label') {
1224 if (NULL === self
::$activityStatus) {
1225 self
::$activityStatus = [];
1227 if (!array_key_exists($column, self
::$activityStatus)) {
1228 self
::$activityStatus[$column] = [];
1230 self
::$activityStatus[$column] = CRM_Core_OptionGroup
::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1233 return self
::$activityStatus[$column];
1237 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1239 * Get all Visibility levels.
1241 * The static array visibility is returned
1244 * @param string $column
1247 * array reference of all Visibility levels.
1249 public static function &visibility($column = 'label') {
1250 if (!isset(self
::$visibility)) {
1251 self
::$visibility = [];
1254 if (!isset(self
::$visibility[$column])) {
1255 self
::$visibility[$column] = CRM_Core_OptionGroup
::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1258 return self
::$visibility[$column];
1262 * @param int $countryID
1263 * @param string $field
1267 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1268 static $_cache = NULL;
1270 $cacheKey = "{$countryID}_{$field}";
1275 if (!empty($_cache[$cacheKey])) {
1276 return $_cache[$cacheKey];
1280 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1281 FROM civicrm_state_province
1282 WHERE country_id = %1
1291 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1294 while ($dao->fetch()) {
1295 $result[$dao->id
] = $dao->name
;
1298 // localise the stateProvince names if in an non-en_US locale
1299 $config = CRM_Core_Config
::singleton();
1300 $tsLocale = CRM_Core_I18n
::getLocale();
1301 if ($tsLocale != '' and $tsLocale != 'en_US') {
1302 $i18n = CRM_Core_I18n
::singleton();
1303 $i18n->localizeArray($result, [
1304 'context' => 'province',
1306 $result = CRM_Utils_Array
::asort($result);
1309 $_cache[$cacheKey] = $result;
1311 CRM_Utils_Hook
::buildStateProvinceForCountry($countryID, $result);
1317 * @param int $stateID
1321 public static function &countyForState($stateID) {
1322 if (is_array($stateID)) {
1323 $states = implode(", ", $stateID);
1325 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1327 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1328 WHERE civicrm_county.state_province_id in ( $states )
1329 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1331 $dao = CRM_Core_DAO
::executeQuery($query);
1334 while ($dao->fetch()) {
1335 $result[$dao->id
] = $dao->abbreviation
. ': ' . $dao->name
;
1340 static $_cache = NULL;
1342 $cacheKey = "{$stateID}_name";
1347 if (!empty($_cache[$cacheKey])) {
1348 return $_cache[$cacheKey];
1352 SELECT civicrm_county.name name, civicrm_county.id id
1354 WHERE state_province_id = %1
1363 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1366 while ($dao->fetch()) {
1367 $result[$dao->id
] = $dao->name
;
1375 * Given a state ID return the country ID, this allows
1376 * us to populate forms and values for downstream code
1378 * @param int $stateID
1381 * the country id that the state belongs to
1383 public static function countryIDForStateID($stateID) {
1384 if (empty($stateID)) {
1390 FROM civicrm_state_province
1393 $params = [1 => [$stateID, 'Integer']];
1395 return CRM_Core_DAO
::singleValueQuery($query, $params);
1399 * Get all types of Greetings.
1401 * The static array of greeting is returned
1405 * Get All Email Greetings - default is to get only active ones.
1407 * @param string $columnName
1410 * array reference of all greetings.
1412 public static function greeting($filter, $columnName = 'label') {
1413 if (!isset(Civi
::$statics[__CLASS__
]['greeting'])) {
1414 Civi
::$statics[__CLASS__
]['greeting'] = [];
1417 $index = $filter['greeting_type'] . '_' . $columnName;
1419 // also add contactType to the array
1420 $contactType = CRM_Utils_Array
::value('contact_type', $filter);
1422 $index .= '_' . $contactType;
1425 if (!CRM_Utils_Array
::value($index, Civi
::$statics[__CLASS__
]['greeting'])) {
1426 $filterCondition = NULL;
1428 $filterVal = 'v.filter =';
1429 switch ($contactType) {
1438 case 'Organization':
1442 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1445 Civi
::$statics[__CLASS__
]['greeting'][$index] = CRM_Core_OptionGroup
::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1448 return Civi
::$statics[__CLASS__
]['greeting'][$index];
1452 * Get all extensions.
1454 * The static array extensions
1456 * FIXME: This is called by civix but not by any core code. We
1457 * should provide an API call which civix can use instead.
1461 * array($fullyQualifiedName => $label) list of extensions
1463 public static function &getExtensions() {
1464 if (!self
::$extensions) {
1465 self
::$extensions = [];
1467 SELECT full_name, label
1468 FROM civicrm_extension
1471 $dao = CRM_Core_DAO
::executeQuery($sql);
1472 while ($dao->fetch()) {
1473 self
::$extensions[$dao->full_name
] = $dao->label
;
1477 return self
::$extensions;
1481 * Get all options values.
1483 * The static array option values is returned
1486 * @param bool $optionGroupName
1487 * Get All Option Group values- default is to get only active ones.
1490 * @param null $condition
1493 * array reference of all Option Group Name
1495 public static function accountOptionValues($optionGroupName, $id = NULL, $condition = NULL) {
1496 $cacheKey = $optionGroupName . '_' . $condition;
1497 if (empty(self
::$accountOptionValues[$cacheKey])) {
1498 self
::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup
::values($optionGroupName, FALSE, FALSE, FALSE, $condition);
1501 return CRM_Utils_Array
::value($id, self
::$accountOptionValues[$cacheKey]);
1504 return self
::$accountOptionValues[$cacheKey];
1508 * Fetch the list of active extensions of type 'module'
1510 * @param bool $fresh
1511 * Whether to forcibly reload extensions list from canonical store.
1514 * array(array('prefix' => $, 'file' => $))
1516 public static function getModuleExtensions($fresh = FALSE) {
1517 return CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles($fresh);
1521 * Get all tax rates.
1523 * The static array tax rates is returned
1526 * array list of tax rates with the financial type
1528 public static function getTaxRates() {
1529 if (!isset(Civi
::$statics[__CLASS__
]['taxRates'])) {
1530 Civi
::$statics[__CLASS__
]['taxRates'] = [];
1531 $option = civicrm_api3('option_value', 'get', [
1533 'option_group_id' => 'account_relationship',
1534 'name' => 'Sales Tax Account is',
1537 if ($option['count'] !== 0) {
1538 if ($option['count'] > 1) {
1539 foreach ($option['values'] as $opt) {
1540 $value[] = $opt['value'];
1544 $value[] = $option['values'][0]['value'];
1546 $where = 'AND efa.account_relationship IN (' . implode(', ', $value) . ' )';
1552 SELECT fa.tax_rate, efa.entity_id
1553 FROM civicrm_entity_financial_account efa
1554 INNER JOIN civicrm_financial_account fa ON fa.id = efa.financial_account_id
1555 WHERE efa.entity_table = 'civicrm_financial_type'
1557 AND fa.is_active = 1";
1558 $dao = CRM_Core_DAO
::executeQuery($sql);
1559 while ($dao->fetch()) {
1560 Civi
::$statics[__CLASS__
]['taxRates'][$dao->entity_id
] = $dao->tax_rate
;
1564 return Civi
::$statics[__CLASS__
]['taxRates'];
1568 * Get participant status class options.
1572 public static function emailOnHoldOptions() {
1575 '1' => ts('On Hold Bounce'),
1576 '2' => ts('On Hold Opt Out'),