3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
48 class CRM_Core_PseudoConstant
{
51 * Static cache for pseudoconstant arrays.
54 private static $cache;
57 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
62 private static $activityType;
68 private static $stateProvince;
74 private static $county;
77 * States/provinces abbreviations
80 private static $stateProvinceAbbreviation = array();
86 private static $country;
92 private static $countryIsoCode;
95 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
100 private static $group;
106 private static $relationshipType;
109 * Civicrm groups that are not smart groups
112 private static $staticGroup;
118 private static $currencyCode;
124 private static $paymentProcessor;
127 * Payment processor types
130 private static $paymentProcessorType;
136 private static $worldRegions;
139 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
144 private static $activityStatus;
150 private static $visibility;
156 private static $greeting;
159 * Extensions of type module
162 private static $extensions;
165 * Financial Account Type
168 private static $accountOptionValues;
171 * Low-level option getter, rarely accessed directly.
172 * NOTE: Rather than calling this function directly use CRM_*_BAO_*::buildOptions()
173 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Pseudoconstant+%28option+list%29+Reference
175 * NOTE: If someone undertakes a refactoring of this, please consider the use-case of
176 * the Setting.getoptions API. There is no DAO/field, but it would be nice to use the
177 * same 'pseudoconstant' struct in *.settings.php. This means loosening the coupling
178 * between $field lookup and the $pseudoconstant evaluation.
180 * @param string $daoName
181 * @param string $fieldName
182 * @param array $params
183 * - name string name of the option group
184 * - flip boolean results are return in id => label format if false
185 * if true, the results are reversed
186 * - grouping boolean if true, return the value in 'grouping' column (currently unsupported for tables other than option_value)
187 * - localize boolean if true, localize the results before returning
188 * - condition string|array add condition(s) to the sql query - will be concatenated using 'AND'
189 * - keyColumn string the column to use for 'id'
190 * - labelColumn string the column to use for 'label'
191 * - orderColumn string the column to use for sorting, defaults to 'weight' column if one exists, else defaults to labelColumn
192 * - onlyActive boolean return only the action option values
193 * - fresh boolean ignore cache entries and go back to DB
194 * @param string $context : Context string
195 * @see CRM_Core_DAO::buildOptionsContext
198 * array on success, FALSE on error.
201 public static function get($daoName, $fieldName, $params = array(), $context = NULL) {
202 CRM_Core_DAO
::buildOptionsContext($context);
203 $flip = !empty($params['flip']);
204 // Merge params with defaults
208 'onlyActive' => ($context == 'validate' ||
$context == 'get') ?
FALSE : TRUE,
210 'context' => $context,
212 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getCanonicalClassName($daoName));
214 // Custom fields are not in the schema
215 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
216 $customField = new CRM_Core_BAO_CustomField();
217 $customField->id
= (int) substr($fieldName, 7);
218 $options = $customField->getOptions($context);
219 if ($options && $flip) {
220 $options = array_flip($options);
222 $customField->free();
226 // Core field: load schema
227 $dao = new $daoName();
228 $fieldSpec = $dao->getFieldSpec($fieldName);
231 // Ensure we have the canonical name for this field
232 $fieldName = CRM_Utils_Array
::value('name', $fieldSpec, $fieldName);
234 // Return false if field doesn't exist.
235 if (empty($fieldSpec)) {
239 elseif (!empty($fieldSpec['pseudoconstant'])) {
240 $pseudoconstant = $fieldSpec['pseudoconstant'];
242 // if callback is specified..
243 if (!empty($pseudoconstant['callback'])) {
244 $fieldOptions = call_user_func(Civi\Core\Resolver
::singleton()->get($pseudoconstant['callback']), $context);
245 //CRM-18223: Allow additions to field options via hook.
246 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $fieldOptions, $params);
247 return $fieldOptions;
250 // Merge params with schema defaults
252 'condition' => CRM_Utils_Array
::value('condition', $pseudoconstant, array()),
253 'keyColumn' => CRM_Utils_Array
::value('keyColumn', $pseudoconstant),
254 'labelColumn' => CRM_Utils_Array
::value('labelColumn', $pseudoconstant),
257 if ($context == 'abbreviate') {
258 switch ($fieldName) {
259 case 'state_province_id':
260 $params['labelColumn'] = 'abbreviation';
264 $params['labelColumn'] = 'iso_code';
271 // Fetch option group from option_value table
272 if (!empty($pseudoconstant['optionGroupName'])) {
273 if ($context == 'validate') {
274 $params['labelColumn'] = 'name';
276 if ($context == 'match') {
277 $params['keyColumn'] = 'name';
279 // Call our generic fn for retrieving from the option_value table
280 $options = CRM_Core_OptionGroup
::values(
281 $pseudoconstant['optionGroupName'],
285 $params['condition'] ?
' AND ' . implode(' AND ', (array) $params['condition']) : NULL,
286 $params['labelColumn'] ?
$params['labelColumn'] : 'label',
287 $params['onlyActive'],
289 $params['keyColumn'] ?
$params['keyColumn'] : 'value',
290 !empty($params['orderColumn']) ?
$params['orderColumn'] : 'weight'
292 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $options, $params);
296 // Fetch options from other tables
297 if (!empty($pseudoconstant['table'])) {
298 // Normalize params so the serialized cache string will be consistent.
299 CRM_Utils_Array
::remove($params, 'flip', 'fresh');
301 $cacheKey = $daoName . $fieldName . serialize($params);
303 // Retrieve cached options
304 if (isset(self
::$cache[$cacheKey]) && empty($params['fresh'])) {
305 $output = self
::$cache[$cacheKey];
308 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($pseudoconstant['table']);
309 if (!class_exists($daoName)) {
312 // Get list of fields for the option table
313 $dao = new $daoName();
314 $availableFields = array_keys($dao->fieldKeys());
317 $select = "SELECT %1 AS id, %2 AS label";
320 $order = "ORDER BY %2";
322 // Use machine name in certain contexts
323 if ($context == 'validate' ||
$context == 'match') {
324 $nameField = $context == 'validate' ?
'labelColumn' : 'keyColumn';
325 if (!empty($pseudoconstant['nameColumn'])) {
326 $params[$nameField] = $pseudoconstant['nameColumn'];
328 elseif (in_array('name', $availableFields)) {
329 $params[$nameField] = 'name';
332 // Condition param can be passed as an sql clause string or an array of clauses
333 if (!empty($params['condition'])) {
334 $wheres[] = implode(' AND ', (array) $params['condition']);
336 // onlyActive param will automatically filter on common flags
337 if (!empty($params['onlyActive'])) {
338 foreach (array('is_active' => 1, 'is_deleted' => 0, 'is_test' => 0, 'is_hidden' => 0) as $flag => $val) {
339 if (in_array($flag, $availableFields)) {
340 $wheres[] = "$flag = $val";
344 // Filter domain specific options
345 if (in_array('domain_id', $availableFields)) {
346 $wheres[] = 'domain_id = ' . CRM_Core_Config
::domainID();
348 $queryParams = array(
349 1 => array($params['keyColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
350 2 => array($params['labelColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
351 3 => array($pseudoconstant['table'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
353 // Add orderColumn param
354 if (!empty($params['orderColumn'])) {
355 $queryParams[4] = array($params['orderColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
);
356 $order = "ORDER BY %4";
358 // Support no sorting if $params[orderColumn] is FALSE
359 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
362 // Default to 'weight' if that column exists
363 elseif (in_array('weight', $availableFields)) {
364 $order = "ORDER BY weight";
368 $query = "$select $from";
370 $query .= " WHERE " . implode($wheres, ' AND ');
372 $query .= ' ' . $order;
373 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
374 while ($dao->fetch()) {
375 $output[$dao->id
] = $dao->label
;
379 if (!empty($params['localize']) ||
$pseudoconstant['table'] == 'civicrm_country' ||
$pseudoconstant['table'] == 'civicrm_state_province') {
380 $I18nParams = array();
381 if ($pseudoconstant['table'] == 'civicrm_country') {
382 $I18nParams['context'] = 'country';
384 if ($pseudoconstant['table'] == 'civicrm_state_province') {
385 $I18nParams['context'] = 'province';
387 $i18n = CRM_Core_I18n
::singleton();
388 $i18n->localizeArray($output, $I18nParams);
389 // Maintain sort by label
390 if ($order == "ORDER BY %2") {
391 CRM_Utils_Array
::asort($output);
394 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $output, $params);
395 self
::$cache[$cacheKey] = $output;
397 return $flip ?
array_flip($output) : $output;
401 // Return "Yes" and "No" for boolean fields
402 elseif (CRM_Utils_Array
::value('type', $fieldSpec) === CRM_Utils_Type
::T_BOOLEAN
) {
403 $output = $context == 'validate' ?
array(0, 1) : CRM_Core_SelectValues
::boolean();
404 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $output, $params);
405 return $flip ?
array_flip($output) : $output;
407 // If we're still here, it's an error. Return FALSE.
412 * Fetch the translated label for a field given its key.
414 * @param string $baoName
415 * @param string $fieldName
416 * @param string|Int $key
418 * TODO: Accept multivalued input?
420 * @return bool|null|string
421 * FALSE if the given field has no associated option list
422 * NULL if the given key has no corresponding option
423 * String if label is found
425 public static function getLabel($baoName, $fieldName, $key) {
426 $values = $baoName::buildOptions($fieldName, 'get');
427 if ($values === FALSE) {
430 return CRM_Utils_Array
::value($key, $values);
434 * Fetch the machine name for a field given its key.
436 * @param string $baoName
437 * @param string $fieldName
438 * @param string|Int $key
440 * @return bool|null|string
441 * FALSE if the given field has no associated option list
442 * NULL if the given key has no corresponding option
443 * String if label is found
445 public static function getName($baoName, $fieldName, $key) {
446 $values = $baoName::buildOptions($fieldName, 'validate');
447 if ($values === FALSE) {
450 return CRM_Utils_Array
::value($key, $values);
454 * Fetch the key for a field option given its name.
456 * @param string $baoName
457 * @param string $fieldName
458 * @param string|Int $value
460 * @return bool|null|string|int
461 * FALSE if the given field has no associated option list
462 * NULL if the given key has no corresponding option
463 * String|Number if key is found
465 public static function getKey($baoName, $fieldName, $value) {
466 $values = $baoName::buildOptions($fieldName, 'validate');
467 if ($values === FALSE) {
470 return CRM_Utils_Array
::key($value, $values);
474 * Lookup the admin page at which a field's option list can be edited
476 * @return string|null
478 public static function getOptionEditUrl($fieldSpec) {
479 // If it's an option group, that's easy
480 if (!empty($fieldSpec['pseudoconstant']['optionGroupName'])) {
481 return 'civicrm/admin/options/' . $fieldSpec['pseudoconstant']['optionGroupName'];
483 // For everything else...
484 elseif (!empty($fieldSpec['pseudoconstant']['table'])) {
485 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($fieldSpec['pseudoconstant']['table']);
489 // We don't have good mapping so have to do a bit of guesswork from the menu
490 list(, $parent, , $child) = explode('_', $daoName);
491 $sql = "SELECT path FROM civicrm_menu
492 WHERE page_callback LIKE '%CRM_Admin_Page_$child%' OR page_callback LIKE '%CRM_{$parent}_Page_$child%'
493 ORDER BY page_callback
495 return CRM_Core_Dao
::singleValueQuery($sql);
501 * DEPRECATED generic populate method.
502 * All pseudoconstant functions that use this method are also @deprecated
504 * The static array $var is populated from the db
505 * using the <b>$name DAO</b>.
507 * Note: any database errors will be trapped by the DAO.
510 * The associative array we will fill.
511 * @param string $name
512 * The name of the DAO.
514 * Get all objects. default is to get only active ones.
515 * @param string $retrieve
516 * The field that we are interested in (normally name, differs in some objects).
517 * @param string $filter
518 * The field that we want to filter the result set with.
519 * @param string $condition
520 * The condition that gets passed to the final query as the WHERE clause.
522 * @param bool $orderby
528 public static function populate(
533 $filter = 'is_active',
539 $cacheKey = "CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}";
540 $cache = CRM_Utils_Cache
::singleton();
541 $var = $cache->get($cacheKey);
542 if ($var && empty($force)) {
546 /* @var CRM_Core_DAO $object */
547 $object = new $name();
549 $object->selectAdd();
550 $object->selectAdd("$key, $retrieve");
552 $object->whereAdd($condition);
556 $object->orderBy($retrieve);
559 $object->orderBy($orderby);
563 $object->$filter = 1;
564 $aclClauses = array_filter($name::getSelectWhereClause());
565 foreach ($aclClauses as $clause) {
566 $object->whereAdd($clause);
572 while ($object->fetch()) {
573 $var[$object->$key] = $object->$retrieve;
576 $cache->set($cacheKey, $var);
580 * Flush given pseudoconstant so it can be reread from db.
581 * nex time it's requested.
584 * @param bool|string $name pseudoconstant to be flushed
586 public static function flush($name = 'cache') {
587 if (isset(self
::$
$name)) {
590 if ($name == 'cache') {
591 CRM_Core_OptionGroup
::flushAll();
592 if (isset(\Civi
::$statics[__CLASS__
])) {
593 unset(\Civi
::$statics[__CLASS__
]);
599 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
601 * Get all Activty types.
603 * The static array activityType is returned
607 * array reference of all activity types.
609 public static function &activityType() {
610 $args = func_get_args();
611 $all = CRM_Utils_Array
::value(0, $args, TRUE);
612 $includeCaseActivities = CRM_Utils_Array
::value(1, $args, FALSE);
613 $reset = CRM_Utils_Array
::value(2, $args, FALSE);
614 $returnColumn = CRM_Utils_Array
::value(3, $args, 'label');
615 $includeCampaignActivities = CRM_Utils_Array
::value(4, $args, FALSE);
616 $onlyComponentActivities = CRM_Utils_Array
::value(5, $args, FALSE);
617 $index = (int) $all . '_' . $returnColumn . '_' . (int) $includeCaseActivities;
618 $index .= '_' . (int) $includeCampaignActivities;
619 $index .= '_' . (int) $onlyComponentActivities;
621 if (NULL === self
::$activityType) {
622 self
::$activityType = array();
625 if (!isset(self
::$activityType[$index]) ||
$reset) {
628 $condition = 'AND filter = 0';
630 $componentClause = " v.component_id IS NULL";
631 if ($onlyComponentActivities) {
632 $componentClause = " v.component_id IS NOT NULL";
635 $componentIds = array();
636 $compInfo = CRM_Core_Component
::getEnabledComponents();
638 // build filter for listing activity types only if their
639 // respective components are enabled
640 foreach ($compInfo as $compName => $compObj) {
641 if ($compName == 'CiviCase') {
642 if ($includeCaseActivities) {
643 $componentIds[] = $compObj->componentID
;
646 elseif ($compName == 'CiviCampaign') {
647 if ($includeCampaignActivities) {
648 $componentIds[] = $compObj->componentID
;
652 $componentIds[] = $compObj->componentID
;
656 if (count($componentIds)) {
657 $componentIds = implode(',', $componentIds);
658 $componentClause = " ($componentClause OR v.component_id IN ($componentIds))";
659 if ($onlyComponentActivities) {
660 $componentClause = " ( v.component_id IN ($componentIds ) )";
663 $condition = $condition . ' AND ' . $componentClause;
665 self
::$activityType[$index] = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
667 return self
::$activityType[$index];
671 * Get all the State/Province from database.
673 * The static array stateProvince is returned, and if it's
674 * called the first time, the <b>State Province DAO</b> is used
675 * to get all the States.
677 * Note: any database errors will be trapped by the DAO.
680 * @param bool|int $id - Optional id to return
685 * array reference of all State/Provinces.
687 public static function &stateProvince($id = FALSE, $limit = TRUE) {
688 if (($id && !CRM_Utils_Array
::value($id, self
::$stateProvince)) ||
!self
::$stateProvince ||
!$id) {
689 $whereClause = FALSE;
691 $countryIsoCodes = self
::countryIsoCode();
692 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
694 foreach ($limitCodes as $code) {
695 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
697 if (!empty($limitIds)) {
698 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
701 $whereClause = FALSE;
704 self
::populate(self
::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
706 // localise the province names if in an non-en_US locale
707 $tsLocale = CRM_Core_I18n
::getLocale();
708 if ($tsLocale != '' and $tsLocale != 'en_US') {
709 $i18n = CRM_Core_I18n
::singleton();
710 $i18n->localizeArray(self
::$stateProvince, array(
711 'context' => 'province',
713 self
::$stateProvince = CRM_Utils_Array
::asort(self
::$stateProvince);
717 if (array_key_exists($id, self
::$stateProvince)) {
718 return self
::$stateProvince[$id];
725 return self
::$stateProvince;
729 * Get all the State/Province abbreviations from the database.
731 * Same as above, except gets the abbreviations instead of the names.
734 * @param bool|int $id - Optional id to return
739 * array reference of all State/Province abbreviations.
741 public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
742 if ($id && is_numeric($id)) {
743 if (!array_key_exists($id, (array) self
::$stateProvinceAbbreviation)) {
744 $query = "SELECT abbreviation
745 FROM civicrm_state_province
753 self
::$stateProvinceAbbreviation[$id] = CRM_Core_DAO
::singleValueQuery($query, $params);
755 return self
::$stateProvinceAbbreviation[$id];
758 $whereClause = FALSE;
761 $countryIsoCodes = self
::countryIsoCode();
762 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
764 foreach ($limitCodes as $code) {
765 $tmpArray = array_keys($countryIsoCodes, $code);
767 if (!empty($tmpArray)) {
768 $limitIds[] = array_shift($tmpArray);
771 if (!empty($limitIds)) {
772 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
775 self
::populate(self
::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
778 return self
::$stateProvinceAbbreviation;
782 * Get all the State/Province abbreviations from the database for the specified country.
784 * @param int $countryID
787 * array of all State/Province abbreviations for the given country.
789 public static function stateProvinceAbbreviationForCountry($countryID) {
790 if (!isset(\Civi
::$statics[__CLASS__
]['stateProvinceAbbreviationForCountry'][$countryID])) {
791 \Civi
::$statics[__CLASS__
]['stateProvinceAbbreviationForCountry'][$countryID] = array();
793 self
::populate(\Civi
::$statics[__CLASS__
]['stateProvinceAbbreviationForCountry'][$countryID], 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', "country_id = " . (int) $countryID, 'abbreviation');
794 return \Civi
::$statics[__CLASS__
]['stateProvinceAbbreviationForCountry'][$countryID];
798 * Get all the State/Province abbreviations from the database for the default country.
801 * array of all State/Province abbreviations for the given country.
803 public static function stateProvinceAbbreviationForDefaultCountry() {
804 return CRM_Core_PseudoConstant
::stateProvinceAbbreviationForCountry(Civi
::settings()->get('defaultContactCountry'));
808 * Get all the countries from database.
810 * The static array country is returned, and if it's
811 * called the first time, the <b>Country DAO</b> is used
812 * to get all the countries.
814 * Note: any database errors will be trapped by the DAO.
817 * @param bool|int $id - Optional id to return
819 * @param bool $applyLimit
822 * array reference of all countries.
824 public static function country($id = FALSE, $applyLimit = TRUE) {
825 if (($id && !CRM_Utils_Array
::value($id, self
::$country)) ||
!self
::$country ||
!$id) {
827 $config = CRM_Core_Config
::singleton();
828 $limitCodes = array();
831 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
832 // (ensuring it's a subset of the legal values)
833 // K/P: We need to fix this, i dont think it works with new setting files
834 $limitCodes = CRM_Core_BAO_Country
::countryLimit();
835 if (!is_array($limitCodes)) {
837 $config->countryLimit
=> 1,
841 $limitCodes = array_intersect(self
::countryIsoCode(), $limitCodes);
844 if (count($limitCodes)) {
845 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
851 self
::populate(self
::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
853 // if default country is set, percolate it to the top
854 if ($config->defaultContactCountry()) {
855 $countryIsoCodes = self
::countryIsoCode();
856 $defaultID = array_search($config->defaultContactCountry(), $countryIsoCodes);
857 if ($defaultID !== FALSE) {
858 $default[$defaultID] = CRM_Utils_Array
::value($defaultID, self
::$country);
859 self
::$country = $default + self
::$country;
863 // localise the country names if in an non-en_US locale
864 $tsLocale = CRM_Core_I18n
::getLocale();
865 if ($tsLocale != '' and $tsLocale != 'en_US') {
866 $i18n = CRM_Core_I18n
::singleton();
867 $i18n->localizeArray(self
::$country, array(
868 'context' => 'country',
870 self
::$country = CRM_Utils_Array
::asort(self
::$country);
874 if (array_key_exists($id, self
::$country)) {
875 return self
::$country[$id];
881 return self
::$country;
885 * Get all the country ISO Code abbreviations from the database.
887 * The static array countryIsoCode is returned, and if it's
888 * called the first time, the <b>Country DAO</b> is used
889 * to get all the countries' ISO codes.
891 * Note: any database errors will be trapped by the DAO.
897 * array reference of all country ISO codes.
899 public static function &countryIsoCode($id = FALSE) {
900 if (!self
::$countryIsoCode) {
901 self
::populate(self
::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
904 if (array_key_exists($id, self
::$countryIsoCode)) {
905 return self
::$countryIsoCode[$id];
908 return CRM_Core_DAO
::$_nullObject;
911 return self
::$countryIsoCode;
915 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
917 * Get all groups from database
919 * The static array group is returned, and if it's
920 * called the first time, the <b>Group DAO</b> is used
921 * to get all the groups.
923 * Note: any database errors will be trapped by the DAO.
925 * @param string $groupType
926 * Type of group(Access/Mailing).
927 * @param bool $excludeHidden
928 * Exclude hidden groups.
932 * array reference of all groups.
934 public static function allGroup($groupType = NULL, $excludeHidden = TRUE) {
935 if ($groupType === 'validate') {
936 // validate gets passed through from getoptions. Handle in the deprecated
937 // fn rather than change the new pattern.
940 $condition = CRM_Contact_BAO_Group
::groupTypeCondition($groupType, $excludeHidden);
941 $groupKey = ($groupType ?
$groupType : 'null') . !empty($excludeHidden);
943 if (!isset(Civi
::$statics[__CLASS__
]['groups']['allGroup'][$groupKey])) {
944 self
::populate(Civi
::$statics[__CLASS__
]['groups']['allGroup'][$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
946 return Civi
::$statics[__CLASS__
]['groups']['allGroup'][$groupKey];
950 * Get all permissioned groups from database.
952 * The static array group is returned, and if it's
953 * called the first time, the <b>Group DAO</b> is used
954 * to get all the groups.
956 * Note: any database errors will be trapped by the DAO.
958 * @param string $groupType
959 * Type of group(Access/Mailing).
960 * @param bool $excludeHidden
961 * Exclude hidden groups.
965 * array reference of all groups.
967 public static function group($groupType = NULL, $excludeHidden = TRUE) {
968 return CRM_Core_Permission
::group($groupType, $excludeHidden);
972 * Fetch groups in a nested format suitable for use in select form element.
973 * @param bool $checkPermissions
974 * @param string|null $groupType
975 * @param bool $excludeHidden
978 public static function nestedGroup($checkPermissions = TRUE, $groupType = NULL, $excludeHidden = TRUE) {
979 $groups = $checkPermissions ? self
::group($groupType, $excludeHidden) : self
::allGroup($groupType, $excludeHidden);
980 return CRM_Contact_BAO_Group
::getGroupsHierarchy($groups, NULL, ' ', TRUE);
984 * Get all permissioned groups from database.
986 * The static array group is returned, and if it's
987 * called the first time, the <b>Group DAO</b> is used
988 * to get all the groups.
990 * Note: any database errors will be trapped by the DAO.
993 * @param bool $onlyPublic
994 * @param null $groupType
995 * @param bool $excludeHidden
998 * array reference of all groups.
1000 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
1001 if (!self
::$staticGroup) {
1002 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
1004 $condition .= " AND visibility != 'User and User Admin Only'";
1008 $condition .= ' AND ' . CRM_Contact_BAO_Group
::groupTypeCondition($groupType);
1011 if ($excludeHidden) {
1012 $condition .= ' AND is_hidden != 1 ';
1015 self
::populate(self
::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
1018 return self
::$staticGroup;
1022 * Get all Relationship Types from database.
1024 * The static array group is returned, and if it's
1025 * called the first time, the <b>RelationshipType DAO</b> is used
1026 * to get all the relationship types.
1028 * Note: any database errors will be trapped by the DAO.
1030 * @param string $valueColumnName
1031 * Db column name/label.
1032 * @param bool $reset
1033 * Reset relationship types if true.
1034 * @param bool $isActive
1035 * Filter by is_active. NULL to disable.
1038 * array reference of all relationship types.
1040 public static function &relationshipType($valueColumnName = 'label', $reset = FALSE, $isActive = 1) {
1041 $cacheKey = $valueColumnName . '::' . $isActive;
1042 if (!CRM_Utils_Array
::value($cacheKey, self
::$relationshipType) ||
$reset) {
1043 self
::$relationshipType[$cacheKey] = array();
1045 //now we have name/label columns CRM-3336
1046 $column_a_b = "{$valueColumnName}_a_b";
1047 $column_b_a = "{$valueColumnName}_b_a";
1049 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1050 $relationshipTypeDAO->selectAdd();
1051 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1052 if ($isActive !== NULL) {
1053 $relationshipTypeDAO->is_active
= $isActive;
1055 $relationshipTypeDAO->find();
1056 while ($relationshipTypeDAO->fetch()) {
1058 self
::$relationshipType[$cacheKey][$relationshipTypeDAO->id
] = array(
1059 'id' => $relationshipTypeDAO->id
,
1060 $column_a_b => $relationshipTypeDAO->$column_a_b,
1061 $column_b_a => $relationshipTypeDAO->$column_b_a,
1062 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1063 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1064 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1065 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1070 return self
::$relationshipType[$cacheKey];
1074 * Get all the ISO 4217 currency codes
1076 * so far, we use this for validation only, so there's no point of putting this into the database
1080 * array reference of all currency codes
1082 public static function ¤cyCode() {
1083 if (!self
::$currencyCode) {
1085 $query = "SELECT name FROM civicrm_currency";
1086 $dao = CRM_Core_DAO
::executeQuery($query);
1087 $currencyCode = array();
1088 while ($dao->fetch()) {
1089 self
::$currencyCode[] = $dao->name
;
1092 return self
::$currencyCode;
1096 * Get all the County from database.
1098 * The static array county is returned, and if it's
1099 * called the first time, the <b>County DAO</b> is used
1100 * to get all the Counties.
1102 * Note: any database errors will be trapped by the DAO.
1105 * @param bool|int $id - Optional id to return
1108 * array reference of all Counties
1110 public static function &county($id = FALSE) {
1111 if (!self
::$county) {
1113 $config = CRM_Core_Config
::singleton();
1114 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1115 self
::populate(self
::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1118 if (array_key_exists($id, self
::$county)) {
1119 return self
::$county[$id];
1122 return CRM_Core_DAO
::$_nullObject;
1125 return self
::$county;
1129 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1130 * Get all active payment processors
1132 * The static array paymentProcessor is returned
1136 * Get payment processors - default is to get only active ones.
1138 * Get test payment processors.
1140 * @param null $additionalCond
1143 * array of all payment processors
1145 public static function paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1146 $condition = "is_test = ";
1147 $condition .= ($test) ?
'1' : '0';
1149 if ($additionalCond) {
1150 $condition .= " AND ( $additionalCond ) ";
1153 // CRM-7178. Make sure we only include payment processors valid in this
1155 $condition .= " AND domain_id = " . CRM_Core_Config
::domainID();
1157 $cacheKey = $condition . '_' . (int) $all;
1158 if (!isset(self
::$paymentProcessor[$cacheKey])) {
1159 self
::populate(self
::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1162 return self
::$paymentProcessor[$cacheKey];
1166 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1168 * The static array paymentProcessorType is returned
1172 * Get payment processors - default is to get only active ones.
1175 * @param string $return
1178 * array of all payment processor types
1180 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1181 $cacheKey = $id . '_' . $return;
1182 if (empty(self
::$paymentProcessorType[$cacheKey])) {
1183 self
::populate(self
::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1185 if ($id && CRM_Utils_Array
::value($id, self
::$paymentProcessorType[$cacheKey])) {
1186 return self
::$paymentProcessorType[$cacheKey][$id];
1188 return self
::$paymentProcessorType[$cacheKey];
1192 * Get all the World Regions from Database.
1198 * array reference of all World Regions
1200 public static function &worldRegion($id = FALSE) {
1201 if (!self
::$worldRegions) {
1202 self
::populate(self
::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1206 if (array_key_exists($id, self
::$worldRegions)) {
1207 return self
::$worldRegions[$id];
1210 return CRM_Core_DAO
::$_nullObject;
1214 return self
::$worldRegions;
1218 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1220 * Get all Activity Statuses.
1222 * The static array activityStatus is returned
1225 * @param string $column
1228 * array reference of all activity statuses
1230 public static function &activityStatus($column = 'label') {
1231 if (NULL === self
::$activityStatus) {
1232 self
::$activityStatus = array();
1234 if (!array_key_exists($column, self
::$activityStatus)) {
1235 self
::$activityStatus[$column] = array();
1237 self
::$activityStatus[$column] = CRM_Core_OptionGroup
::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1240 return self
::$activityStatus[$column];
1244 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1246 * Get all Visibility levels.
1248 * The static array visibility is returned
1251 * @param string $column
1254 * array reference of all Visibility levels.
1256 public static function &visibility($column = 'label') {
1257 if (!isset(self
::$visibility)) {
1258 self
::$visibility = array();
1261 if (!isset(self
::$visibility[$column])) {
1262 self
::$visibility[$column] = CRM_Core_OptionGroup
::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1265 return self
::$visibility[$column];
1269 * @param int $countryID
1270 * @param string $field
1274 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1275 static $_cache = NULL;
1277 $cacheKey = "{$countryID}_{$field}";
1282 if (!empty($_cache[$cacheKey])) {
1283 return $_cache[$cacheKey];
1287 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1288 FROM civicrm_state_province
1289 WHERE country_id = %1
1298 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1301 while ($dao->fetch()) {
1302 $result[$dao->id
] = $dao->name
;
1305 // localise the stateProvince names if in an non-en_US locale
1306 $config = CRM_Core_Config
::singleton();
1307 $tsLocale = CRM_Core_I18n
::getLocale();
1308 if ($tsLocale != '' and $tsLocale != 'en_US') {
1309 $i18n = CRM_Core_I18n
::singleton();
1310 $i18n->localizeArray($result, array(
1311 'context' => 'province',
1313 $result = CRM_Utils_Array
::asort($result);
1316 $_cache[$cacheKey] = $result;
1318 CRM_Utils_Hook
::buildStateProvinceForCountry($countryID, $result);
1324 * @param int $stateID
1328 public static function &countyForState($stateID) {
1329 if (is_array($stateID)) {
1330 $states = implode(", ", $stateID);
1332 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1334 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1335 WHERE civicrm_county.state_province_id in ( $states )
1336 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1338 $dao = CRM_Core_DAO
::executeQuery($query);
1341 while ($dao->fetch()) {
1342 $result[$dao->id
] = $dao->abbreviation
. ': ' . $dao->name
;
1347 static $_cache = NULL;
1349 $cacheKey = "{$stateID}_name";
1354 if (!empty($_cache[$cacheKey])) {
1355 return $_cache[$cacheKey];
1359 SELECT civicrm_county.name name, civicrm_county.id id
1361 WHERE state_province_id = %1
1370 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1373 while ($dao->fetch()) {
1374 $result[$dao->id
] = $dao->name
;
1382 * Given a state ID return the country ID, this allows
1383 * us to populate forms and values for downstream code
1385 * @param int $stateID
1388 * the country id that the state belongs to
1390 public static function countryIDForStateID($stateID) {
1391 if (empty($stateID)) {
1397 FROM civicrm_state_province
1400 $params = array(1 => array($stateID, 'Integer'));
1402 return CRM_Core_DAO
::singleValueQuery($query, $params);
1406 * Get all types of Greetings.
1408 * The static array of greeting is returned
1412 * Get All Email Greetings - default is to get only active ones.
1414 * @param string $columnName
1417 * array reference of all greetings.
1419 public static function greeting($filter, $columnName = 'label') {
1420 if (!isset(Civi
::$statics[__CLASS__
]['greeting'])) {
1421 Civi
::$statics[__CLASS__
]['greeting'] = array();
1424 $index = $filter['greeting_type'] . '_' . $columnName;
1426 // also add contactType to the array
1427 $contactType = CRM_Utils_Array
::value('contact_type', $filter);
1429 $index .= '_' . $contactType;
1432 if (!CRM_Utils_Array
::value($index, Civi
::$statics[__CLASS__
]['greeting'])) {
1433 $filterCondition = NULL;
1435 $filterVal = 'v.filter =';
1436 switch ($contactType) {
1445 case 'Organization':
1449 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1452 Civi
::$statics[__CLASS__
]['greeting'][$index] = CRM_Core_OptionGroup
::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1455 return Civi
::$statics[__CLASS__
]['greeting'][$index];
1459 * Get all extensions.
1461 * The static array extensions
1463 * FIXME: This is called by civix but not by any core code. We
1464 * should provide an API call which civix can use instead.
1468 * array($fullyQualifiedName => $label) list of extensions
1470 public static function &getExtensions() {
1471 if (!self
::$extensions) {
1472 self
::$extensions = array();
1474 SELECT full_name, label
1475 FROM civicrm_extension
1478 $dao = CRM_Core_DAO
::executeQuery($sql);
1479 while ($dao->fetch()) {
1480 self
::$extensions[$dao->full_name
] = $dao->label
;
1484 return self
::$extensions;
1488 * Get all options values.
1490 * The static array option values is returned
1493 * @param bool $optionGroupName
1494 * Get All Option Group values- default is to get only active ones.
1497 * @param null $condition
1500 * array reference of all Option Group Name
1502 public static function accountOptionValues($optionGroupName, $id = NULL, $condition = NULL) {
1503 $cacheKey = $optionGroupName . '_' . $condition;
1504 if (empty(self
::$accountOptionValues[$cacheKey])) {
1505 self
::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup
::values($optionGroupName, FALSE, FALSE, FALSE, $condition);
1508 return CRM_Utils_Array
::value($id, self
::$accountOptionValues[$cacheKey]);
1511 return self
::$accountOptionValues[$cacheKey];
1515 * Fetch the list of active extensions of type 'module'
1517 * @param bool $fresh
1518 * Whether to forcibly reload extensions list from canonical store.
1521 * array(array('prefix' => $, 'file' => $))
1523 public static function getModuleExtensions($fresh = FALSE) {
1524 return CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles($fresh);
1529 * Get all tax rates.
1531 * The static array tax rates is returned
1534 * array list of tax rates with the financial type
1536 public static function getTaxRates() {
1537 if (!isset(Civi
::$statics[__CLASS__
]['taxRates'])) {
1538 Civi
::$statics[__CLASS__
]['taxRates'] = array();
1539 $option = civicrm_api3('option_value', 'get', array(
1541 'option_group_id' => 'account_relationship',
1542 'name' => 'Sales Tax Account is',
1545 if ($option['count'] !== 0) {
1546 if ($option['count'] > 1) {
1547 foreach ($option['values'] as $opt) {
1548 $value[] = $opt['value'];
1552 $value[] = $option['values'][0]['value'];
1554 $where = 'AND efa.account_relationship IN (' . implode(', ', $value) . ' )';
1560 SELECT fa.tax_rate, efa.entity_id
1561 FROM civicrm_entity_financial_account efa
1562 INNER JOIN civicrm_financial_account fa ON fa.id = efa.financial_account_id
1563 WHERE efa.entity_table = 'civicrm_financial_type'
1565 AND fa.is_active = 1";
1566 $dao = CRM_Core_DAO
::executeQuery($sql);
1567 while ($dao->fetch()) {
1568 Civi
::$statics[__CLASS__
]['taxRates'][$dao->entity_id
] = $dao->tax_rate
;
1572 return Civi
::$statics[__CLASS__
]['taxRates'];