3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
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;
162 private static $greetingDefaults;
165 * Extensions of type module
168 private static $extensions;
171 * Financial Account Type
174 private static $accountOptionValues;
177 * Low-level option getter, rarely accessed directly.
178 * NOTE: Rather than calling this function directly use CRM_*_BAO_*::buildOptions()
179 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Pseudoconstant+%28option+list%29+Reference
181 * NOTE: If someone undertakes a refactoring of this, please consider the use-case of
182 * the Setting.getoptions API. There is no DAO/field, but it would be nice to use the
183 * same 'pseudoconstant' struct in *.settings.php. This means loosening the coupling
184 * between $field lookup and the $pseudoconstant evaluation.
186 * @param string $daoName
187 * @param string $fieldName
188 * @param array $params
189 * - name string name of the option group
190 * - flip boolean results are return in id => label format if false
191 * if true, the results are reversed
192 * - grouping boolean if true, return the value in 'grouping' column (currently unsupported for tables other than option_value)
193 * - localize boolean if true, localize the results before returning
194 * - condition string|array add condition(s) to the sql query - will be concatenated using 'AND'
195 * - keyColumn string the column to use for 'id'
196 * - labelColumn string the column to use for 'label'
197 * - orderColumn string the column to use for sorting, defaults to 'weight' column if one exists, else defaults to labelColumn
198 * - onlyActive boolean return only the action option values
199 * - fresh boolean ignore cache entries and go back to DB
200 * @param string $context : Context string
203 * array on success, FALSE on error.
206 public static function get($daoName, $fieldName, $params = array(), $context = NULL) {
207 CRM_Core_DAO
::buildOptionsContext($context);
208 $flip = !empty($params['flip']);
209 // Merge params with defaults
213 'onlyActive' => ($context == 'validate' ||
$context == 'get') ?
FALSE : TRUE,
215 'context' => $context,
217 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getCanonicalClassName($daoName));
219 // Custom fields are not in the schema
220 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
221 $customField = new CRM_Core_BAO_CustomField();
222 $customField->id
= (int) substr($fieldName, 7);
223 $options = $customField->getOptions();
224 if ($options && $flip) {
225 $options = array_flip($options);
227 $customField->free();
231 // Core field: load schema
232 $dao = new $daoName();
233 $fieldSpec = $dao->getFieldSpec($fieldName);
236 // Ensure we have the canonical name for this field
237 $fieldName = CRM_Utils_Array
::value('name', $fieldSpec, $fieldName);
239 // Return false if field doesn't exist.
240 if (empty($fieldSpec)) {
244 elseif (!empty($fieldSpec['pseudoconstant'])) {
245 $pseudoconstant = $fieldSpec['pseudoconstant'];
247 // if callback is specified..
248 if (!empty($pseudoconstant['callback'])) {
249 $fieldOptions = call_user_func(Civi\Core\Resolver
::singleton()->get($pseudoconstant['callback']));
250 //CRM-18223: Allow additions to field options via hook.
251 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $fieldOptions, $params);
252 return $fieldOptions;
255 // Merge params with schema defaults
257 'condition' => CRM_Utils_Array
::value('condition', $pseudoconstant, array()),
258 'keyColumn' => CRM_Utils_Array
::value('keyColumn', $pseudoconstant),
259 'labelColumn' => CRM_Utils_Array
::value('labelColumn', $pseudoconstant),
262 if ($context == 'abbreviate') {
263 switch ($fieldName) {
264 case 'state_province_id':
265 $params['labelColumn'] = 'abbreviation';
269 $params['labelColumn'] = 'iso_code';
276 // Fetch option group from option_value table
277 if (!empty($pseudoconstant['optionGroupName'])) {
278 if ($context == 'validate') {
279 $params['labelColumn'] = 'name';
281 if ($context == 'match') {
282 $params['keyColumn'] = 'name';
284 // Call our generic fn for retrieving from the option_value table
285 $options = CRM_Core_OptionGroup
::values(
286 $pseudoconstant['optionGroupName'],
290 $params['condition'] ?
' AND ' . implode(' AND ', (array) $params['condition']) : NULL,
291 $params['labelColumn'] ?
$params['labelColumn'] : 'label',
292 $params['onlyActive'],
294 $params['keyColumn'] ?
$params['keyColumn'] : 'value',
295 !empty($params['orderColumn']) ?
$params['orderColumn'] : 'weight'
297 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $options, $params);
301 // Fetch options from other tables
302 if (!empty($pseudoconstant['table'])) {
303 // Normalize params so the serialized cache string will be consistent.
304 CRM_Utils_Array
::remove($params, 'flip', 'fresh');
306 $cacheKey = $daoName . $fieldName . serialize($params);
308 // Retrieve cached options
309 if (isset(self
::$cache[$cacheKey]) && empty($params['fresh'])) {
310 $output = self
::$cache[$cacheKey];
313 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($pseudoconstant['table']);
314 if (!class_exists($daoName)) {
317 // Get list of fields for the option table
318 $dao = new $daoName();
319 $availableFields = array_keys($dao->fieldKeys());
322 $select = "SELECT %1 AS id, %2 AS label";
325 $order = "ORDER BY %2";
327 // Use machine name in certain contexts
328 if ($context == 'validate' ||
$context == 'match') {
329 $nameField = $context == 'validate' ?
'labelColumn' : 'keyColumn';
330 if (!empty($pseudoconstant['nameColumn'])) {
331 $params[$nameField] = $pseudoconstant['nameColumn'];
333 elseif (in_array('name', $availableFields)) {
334 $params[$nameField] = 'name';
337 // Condition param can be passed as an sql clause string or an array of clauses
338 if (!empty($params['condition'])) {
339 $wheres[] = implode(' AND ', (array) $params['condition']);
341 // onlyActive param will automatically filter on common flags
342 if (!empty($params['onlyActive'])) {
343 foreach (array('is_active' => 1, 'is_deleted' => 0, 'is_test' => 0, 'is_hidden' => 0) as $flag => $val) {
344 if (in_array($flag, $availableFields)) {
345 $wheres[] = "$flag = $val";
349 // Filter domain specific options
350 if (in_array('domain_id', $availableFields)) {
351 $wheres[] = 'domain_id = ' . CRM_Core_Config
::domainID();
353 $queryParams = array(
354 1 => array($params['keyColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
355 2 => array($params['labelColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
356 3 => array($pseudoconstant['table'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
358 // Add orderColumn param
359 if (!empty($params['orderColumn'])) {
360 $queryParams[4] = array($params['orderColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
);
361 $order = "ORDER BY %4";
363 // Support no sorting if $params[orderColumn] is FALSE
364 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
367 // Default to 'weight' if that column exists
368 elseif (in_array('weight', $availableFields)) {
369 $order = "ORDER BY weight";
373 $query = "$select $from";
375 $query .= " WHERE " . implode($wheres, ' AND ');
377 $query .= ' ' . $order;
378 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
379 while ($dao->fetch()) {
380 $output[$dao->id
] = $dao->label
;
384 if (!empty($params['localize']) ||
$pseudoconstant['table'] == 'civicrm_country' ||
$pseudoconstant['table'] == 'civicrm_state_province') {
385 $I18nParams = array();
386 if ($pseudoconstant['table'] == 'civicrm_country') {
387 $I18nParams['context'] = 'country';
389 if ($pseudoconstant['table'] == 'civicrm_state_province') {
390 $I18nParams['context'] = 'province';
392 $i18n = CRM_Core_I18n
::singleton();
393 $i18n->localizeArray($output, $I18nParams);
394 // Maintain sort by label
395 if ($order == "ORDER BY %2") {
396 CRM_Utils_Array
::asort($output);
399 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $output, $params);
400 self
::$cache[$cacheKey] = $output;
402 return $flip ?
array_flip($output) : $output;
406 // Return "Yes" and "No" for boolean fields
407 elseif (CRM_Utils_Array
::value('type', $fieldSpec) === CRM_Utils_Type
::T_BOOLEAN
) {
408 $output = $context == 'validate' ?
array(0, 1) : CRM_Core_SelectValues
::boolean();
409 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $output, $params);
410 return $flip ?
array_flip($output) : $output;
412 // If we're still here, it's an error. Return FALSE.
417 * Fetch the translated label for a field given its key.
419 * @param string $baoName
420 * @param string $fieldName
421 * @param string|Int $key
423 * TODO: Accept multivalued input?
425 * @return bool|null|string
426 * FALSE if the given field has no associated option list
427 * NULL if the given key has no corresponding option
428 * String if label is found
430 public static function getLabel($baoName, $fieldName, $key) {
431 $values = $baoName::buildOptions($fieldName, 'get');
432 if ($values === FALSE) {
435 return CRM_Utils_Array
::value($key, $values);
439 * Fetch the machine name for a field given its key.
441 * @param string $baoName
442 * @param string $fieldName
443 * @param string|Int $key
445 * @return bool|null|string
446 * FALSE if the given field has no associated option list
447 * NULL if the given key has no corresponding option
448 * String if label is found
450 public static function getName($baoName, $fieldName, $key) {
451 $values = $baoName::buildOptions($fieldName, 'validate');
452 if ($values === FALSE) {
455 return CRM_Utils_Array
::value($key, $values);
459 * Fetch the key for a field option given its name.
461 * @param string $baoName
462 * @param string $fieldName
463 * @param string|Int $value
465 * @return bool|null|string|int
466 * FALSE if the given field has no associated option list
467 * NULL if the given key has no corresponding option
468 * String|Number if key is found
470 public static function getKey($baoName, $fieldName, $value) {
471 $values = $baoName::buildOptions($fieldName, 'validate');
472 if ($values === FALSE) {
475 return CRM_Utils_Array
::key($value, $values);
479 * Lookup the admin page at which a field's option list can be edited
481 * @return string|null
483 public static function getOptionEditUrl($fieldSpec) {
484 // If it's an option group, that's easy
485 if (!empty($fieldSpec['pseudoconstant']['optionGroupName'])) {
486 return 'civicrm/admin/options/' . $fieldSpec['pseudoconstant']['optionGroupName'];
488 // For everything else...
489 elseif (!empty($fieldSpec['pseudoconstant']['table'])) {
490 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($fieldSpec['pseudoconstant']['table']);
494 // We don't have good mapping so have to do a bit of guesswork from the menu
495 list(, $parent, , $child) = explode('_', $daoName);
496 $sql = "SELECT path FROM civicrm_menu
497 WHERE page_callback LIKE '%CRM_Admin_Page_$child%' OR page_callback LIKE '%CRM_{$parent}_Page_$child%'
498 ORDER BY page_callback
500 return CRM_Core_Dao
::singleValueQuery($sql);
506 * DEPRECATED generic populate method.
507 * All pseudoconstant functions that use this method are also @deprecated
509 * The static array $var is populated from the db
510 * using the <b>$name DAO</b>.
512 * Note: any database errors will be trapped by the DAO.
515 * The associative array we will fill.
516 * @param string $name
517 * The name of the DAO.
519 * Get all objects. default is to get only active ones.
520 * @param string $retrieve
521 * The field that we are interested in (normally name, differs in some objects).
522 * @param string $filter
523 * The field that we want to filter the result set with.
524 * @param string $condition
525 * The condition that gets passed to the final query as the WHERE clause.
527 * @param bool $orderby
533 public static function populate(
538 $filter = 'is_active',
544 $cacheKey = "CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}";
545 $cache = CRM_Utils_Cache
::singleton();
546 $var = $cache->get($cacheKey);
547 if ($var && empty($force)) {
551 $object = new $name();
553 $object->selectAdd();
554 $object->selectAdd("$key, $retrieve");
556 $object->whereAdd($condition);
560 $object->orderBy($retrieve);
563 $object->orderBy($orderby);
567 $object->$filter = 1;
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();
596 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
598 * Get all Activty types.
600 * The static array activityType is returned
604 * array reference of all activity types.
606 public static function &activityType() {
607 $args = func_get_args();
608 $all = CRM_Utils_Array
::value(0, $args, TRUE);
609 $includeCaseActivities = CRM_Utils_Array
::value(1, $args, FALSE);
610 $reset = CRM_Utils_Array
::value(2, $args, FALSE);
611 $returnColumn = CRM_Utils_Array
::value(3, $args, 'label');
612 $includeCampaignActivities = CRM_Utils_Array
::value(4, $args, FALSE);
613 $onlyComponentActivities = CRM_Utils_Array
::value(5, $args, FALSE);
614 $index = (int) $all . '_' . $returnColumn . '_' . (int) $includeCaseActivities;
615 $index .= '_' . (int) $includeCampaignActivities;
616 $index .= '_' . (int) $onlyComponentActivities;
618 if (NULL === self
::$activityType) {
619 self
::$activityType = array();
622 if (!isset(self
::$activityType[$index]) ||
$reset) {
625 $condition = 'AND filter = 0';
627 $componentClause = " v.component_id IS NULL";
628 if ($onlyComponentActivities) {
629 $componentClause = " v.component_id IS NOT NULL";
632 $componentIds = array();
633 $compInfo = CRM_Core_Component
::getEnabledComponents();
635 // build filter for listing activity types only if their
636 // respective components are enabled
637 foreach ($compInfo as $compName => $compObj) {
638 if ($compName == 'CiviCase') {
639 if ($includeCaseActivities) {
640 $componentIds[] = $compObj->componentID
;
643 elseif ($compName == 'CiviCampaign') {
644 if ($includeCampaignActivities) {
645 $componentIds[] = $compObj->componentID
;
649 $componentIds[] = $compObj->componentID
;
653 if (count($componentIds)) {
654 $componentIds = implode(',', $componentIds);
655 $componentClause = " ($componentClause OR v.component_id IN ($componentIds))";
656 if ($onlyComponentActivities) {
657 $componentClause = " ( v.component_id IN ($componentIds ) )";
660 $condition = $condition . ' AND ' . $componentClause;
662 self
::$activityType[$index] = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
664 return self
::$activityType[$index];
668 * Get all the State/Province from database.
670 * The static array stateProvince is returned, and if it's
671 * called the first time, the <b>State Province DAO</b> is used
672 * to get all the States.
674 * Note: any database errors will be trapped by the DAO.
677 * @param bool|int $id - Optional id to return
682 * array reference of all State/Provinces.
684 public static function &stateProvince($id = FALSE, $limit = TRUE) {
685 if (($id && !CRM_Utils_Array
::value($id, self
::$stateProvince)) ||
!self
::$stateProvince ||
!$id) {
686 $whereClause = FALSE;
688 $countryIsoCodes = self
::countryIsoCode();
689 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
691 foreach ($limitCodes as $code) {
692 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
694 if (!empty($limitIds)) {
695 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
698 $whereClause = FALSE;
701 self
::populate(self
::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
703 // localise the province names if in an non-en_US locale
704 $tsLocale = CRM_Core_I18n
::getLocale();
705 if ($tsLocale != '' and $tsLocale != 'en_US') {
706 $i18n = CRM_Core_I18n
::singleton();
707 $i18n->localizeArray(self
::$stateProvince, array(
708 'context' => 'province',
710 self
::$stateProvince = CRM_Utils_Array
::asort(self
::$stateProvince);
714 if (array_key_exists($id, self
::$stateProvince)) {
715 return self
::$stateProvince[$id];
722 return self
::$stateProvince;
726 * Get all the State/Province abbreviations from the database.
728 * Same as above, except gets the abbreviations instead of the names.
731 * @param bool|int $id - Optional id to return
736 * array reference of all State/Province abbreviations.
738 public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
739 if ($id && is_numeric($id)) {
740 if (!array_key_exists($id, (array) self
::$stateProvinceAbbreviation)) {
741 $query = "SELECT abbreviation
742 FROM civicrm_state_province
750 self
::$stateProvinceAbbreviation[$id] = CRM_Core_DAO
::singleValueQuery($query, $params);
752 return self
::$stateProvinceAbbreviation[$id];
755 $whereClause = FALSE;
758 $countryIsoCodes = self
::countryIsoCode();
759 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
761 foreach ($limitCodes as $code) {
762 $tmpArray = array_keys($countryIsoCodes, $code);
764 if (!empty($tmpArray)) {
765 $limitIds[] = array_shift($tmpArray);
768 if (!empty($limitIds)) {
769 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
772 self
::populate(self
::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
775 return self
::$stateProvinceAbbreviation;
779 * Get all the countries from database.
781 * The static array country is returned, and if it's
782 * called the first time, the <b>Country DAO</b> is used
783 * to get all the countries.
785 * Note: any database errors will be trapped by the DAO.
788 * @param bool|int $id - Optional id to return
790 * @param bool $applyLimit
793 * array reference of all countries.
795 public static function country($id = FALSE, $applyLimit = TRUE) {
796 if (($id && !CRM_Utils_Array
::value($id, self
::$country)) ||
!self
::$country ||
!$id) {
798 $config = CRM_Core_Config
::singleton();
799 $limitCodes = array();
802 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
803 // (ensuring it's a subset of the legal values)
804 // K/P: We need to fix this, i dont think it works with new setting files
805 $limitCodes = CRM_Core_BAO_Country
::countryLimit();
806 if (!is_array($limitCodes)) {
808 $config->countryLimit
=> 1,
812 $limitCodes = array_intersect(self
::countryIsoCode(), $limitCodes);
815 if (count($limitCodes)) {
816 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
822 self
::populate(self
::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
824 // if default country is set, percolate it to the top
825 if ($config->defaultContactCountry()) {
826 $countryIsoCodes = self
::countryIsoCode();
827 $defaultID = array_search($config->defaultContactCountry(), $countryIsoCodes);
828 if ($defaultID !== FALSE) {
829 $default[$defaultID] = CRM_Utils_Array
::value($defaultID, self
::$country);
830 self
::$country = $default + self
::$country;
834 // localise the country names if in an non-en_US locale
835 $tsLocale = CRM_Core_I18n
::getLocale();
836 if ($tsLocale != '' and $tsLocale != 'en_US') {
837 $i18n = CRM_Core_I18n
::singleton();
838 $i18n->localizeArray(self
::$country, array(
839 'context' => 'country',
841 self
::$country = CRM_Utils_Array
::asort(self
::$country);
845 if (array_key_exists($id, self
::$country)) {
846 return self
::$country[$id];
849 return CRM_Core_DAO
::$_nullObject;
852 return self
::$country;
856 * Get all the country ISO Code abbreviations from the database.
858 * The static array countryIsoCode is returned, and if it's
859 * called the first time, the <b>Country DAO</b> is used
860 * to get all the countries' ISO codes.
862 * Note: any database errors will be trapped by the DAO.
868 * array reference of all country ISO codes.
870 public static function &countryIsoCode($id = FALSE) {
871 if (!self
::$countryIsoCode) {
872 self
::populate(self
::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
875 if (array_key_exists($id, self
::$countryIsoCode)) {
876 return self
::$countryIsoCode[$id];
879 return CRM_Core_DAO
::$_nullObject;
882 return self
::$countryIsoCode;
886 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
888 * Get all groups from database
890 * The static array group is returned, and if it's
891 * called the first time, the <b>Group DAO</b> is used
892 * to get all the groups.
894 * Note: any database errors will be trapped by the DAO.
896 * @param string $groupType
897 * Type of group(Access/Mailing).
898 * @param bool $excludeHidden
899 * Exclude hidden groups.
903 * array reference of all groups.
905 public static function allGroup($groupType = NULL, $excludeHidden = TRUE) {
906 $condition = CRM_Contact_BAO_Group
::groupTypeCondition($groupType, $excludeHidden);
909 self
::$group = array();
912 $groupKey = ($groupType ?
$groupType : 'null') . !empty($excludeHidden);
914 if (!isset(self
::$group[$groupKey])) {
915 self
::$group[$groupKey] = NULL;
916 self
::populate(self
::$group[$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
918 return self
::$group[$groupKey];
922 * Get all permissioned groups from database.
924 * The static array group is returned, and if it's
925 * called the first time, the <b>Group DAO</b> is used
926 * to get all the groups.
928 * Note: any database errors will be trapped by the DAO.
930 * @param string $groupType
931 * Type of group(Access/Mailing).
932 * @param bool $excludeHidden
933 * Exclude hidden groups.
937 * array reference of all groups.
939 public static function group($groupType = NULL, $excludeHidden = TRUE) {
940 return CRM_Core_Permission
::group($groupType, $excludeHidden);
944 * Fetch groups in a nested format suitable for use in select form element.
945 * @param bool $checkPermissions
946 * @param string|null $groupType
947 * @param bool $excludeHidden
950 public static function nestedGroup($checkPermissions = TRUE, $groupType = NULL, $excludeHidden = TRUE) {
951 $groups = $checkPermissions ? self
::group($groupType, $excludeHidden) : self
::allGroup($groupType, $excludeHidden);
952 return CRM_Contact_BAO_Group
::getGroupsHierarchy($groups, NULL, ' ', TRUE);
956 * Get all permissioned groups from database.
958 * The static array group is returned, and if it's
959 * called the first time, the <b>Group DAO</b> is used
960 * to get all the groups.
962 * Note: any database errors will be trapped by the DAO.
965 * @param bool $onlyPublic
966 * @param null $groupType
967 * @param bool $excludeHidden
970 * array reference of all groups.
972 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
973 if (!self
::$staticGroup) {
974 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
976 $condition .= " AND visibility != 'User and User Admin Only'";
980 $condition .= ' AND ' . CRM_Contact_BAO_Group
::groupTypeCondition($groupType);
983 if ($excludeHidden) {
984 $condition .= ' AND is_hidden != 1 ';
987 self
::populate(self
::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
990 return self
::$staticGroup;
994 * Get all Relationship Types from database.
996 * The static array group is returned, and if it's
997 * called the first time, the <b>RelationshipType DAO</b> is used
998 * to get all the relationship types.
1000 * Note: any database errors will be trapped by the DAO.
1002 * @param string $valueColumnName
1003 * Db column name/label.
1004 * @param bool $reset
1005 * Reset relationship types if true.
1006 * @param bool|NULL $isActive
1007 * Filter by is_active. NULL to disable.
1010 * array reference of all relationship types.
1012 public static function &relationshipType($valueColumnName = 'label', $reset = FALSE, $isActive = 1) {
1013 $cacheKey = $valueColumnName . '::' . $isActive;
1014 if (!CRM_Utils_Array
::value($cacheKey, self
::$relationshipType) ||
$reset) {
1015 self
::$relationshipType[$cacheKey] = array();
1017 //now we have name/label columns CRM-3336
1018 $column_a_b = "{$valueColumnName}_a_b";
1019 $column_b_a = "{$valueColumnName}_b_a";
1021 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1022 $relationshipTypeDAO->selectAdd();
1023 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1024 if ($isActive !== NULL) {
1025 $relationshipTypeDAO->is_active
= $isActive;
1027 $relationshipTypeDAO->find();
1028 while ($relationshipTypeDAO->fetch()) {
1030 self
::$relationshipType[$cacheKey][$relationshipTypeDAO->id
] = array(
1031 'id' => $relationshipTypeDAO->id
,
1032 $column_a_b => $relationshipTypeDAO->$column_a_b,
1033 $column_b_a => $relationshipTypeDAO->$column_b_a,
1034 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1035 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1036 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1037 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1042 return self
::$relationshipType[$cacheKey];
1046 * Get all the ISO 4217 currency codes
1048 * so far, we use this for validation only, so there's no point of putting this into the database
1052 * array reference of all currency codes
1054 public static function ¤cyCode() {
1055 if (!self
::$currencyCode) {
1056 self
::$currencyCode = array(
1326 return self
::$currencyCode;
1330 * Get all the County from database.
1332 * The static array county is returned, and if it's
1333 * called the first time, the <b>County DAO</b> is used
1334 * to get all the Counties.
1336 * Note: any database errors will be trapped by the DAO.
1339 * @param bool|int $id - Optional id to return
1342 * array reference of all Counties
1344 public static function &county($id = FALSE) {
1345 if (!self
::$county) {
1347 $config = CRM_Core_Config
::singleton();
1348 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1349 self
::populate(self
::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1352 if (array_key_exists($id, self
::$county)) {
1353 return self
::$county[$id];
1356 return CRM_Core_DAO
::$_nullObject;
1359 return self
::$county;
1363 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1364 * Get all active payment processors
1366 * The static array paymentProcessor is returned
1370 * Get payment processors - default is to get only active ones.
1372 * Get test payment processors.
1374 * @param null $additionalCond
1377 * array of all payment processors
1379 public static function paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1380 $condition = "is_test = ";
1381 $condition .= ($test) ?
'1' : '0';
1383 if ($additionalCond) {
1384 $condition .= " AND ( $additionalCond ) ";
1387 // CRM-7178. Make sure we only include payment processors valid in this
1389 $condition .= " AND domain_id = " . CRM_Core_Config
::domainID();
1391 $cacheKey = $condition . '_' . (int) $all;
1392 if (!isset(self
::$paymentProcessor[$cacheKey])) {
1393 self
::populate(self
::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1396 return self
::$paymentProcessor[$cacheKey];
1400 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1402 * The static array paymentProcessorType is returned
1406 * Get payment processors - default is to get only active ones.
1409 * @param string $return
1412 * array of all payment processor types
1414 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1415 $cacheKey = $id . '_' . $return;
1416 if (empty(self
::$paymentProcessorType[$cacheKey])) {
1417 self
::populate(self
::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1419 if ($id && CRM_Utils_Array
::value($id, self
::$paymentProcessorType[$cacheKey])) {
1420 return self
::$paymentProcessorType[$cacheKey][$id];
1422 return self
::$paymentProcessorType[$cacheKey];
1426 * Get all the World Regions from Database.
1432 * array reference of all World Regions
1434 public static function &worldRegion($id = FALSE) {
1435 if (!self
::$worldRegions) {
1436 self
::populate(self
::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1440 if (array_key_exists($id, self
::$worldRegions)) {
1441 return self
::$worldRegions[$id];
1444 return CRM_Core_DAO
::$_nullObject;
1448 return self
::$worldRegions;
1452 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1454 * Get all Activity Statuses.
1456 * The static array activityStatus is returned
1459 * @param string $column
1462 * array reference of all activity statuses
1464 public static function &activityStatus($column = 'label') {
1465 if (NULL === self
::$activityStatus) {
1466 self
::$activityStatus = array();
1468 if (!array_key_exists($column, self
::$activityStatus)) {
1469 self
::$activityStatus[$column] = array();
1471 self
::$activityStatus[$column] = CRM_Core_OptionGroup
::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1474 return self
::$activityStatus[$column];
1478 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1480 * Get all Visibility levels.
1482 * The static array visibility is returned
1485 * @param string $column
1488 * array reference of all Visibility levels.
1490 public static function &visibility($column = 'label') {
1491 if (!isset(self
::$visibility)) {
1492 self
::$visibility = array();
1495 if (!isset(self
::$visibility[$column])) {
1496 self
::$visibility[$column] = CRM_Core_OptionGroup
::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1499 return self
::$visibility[$column];
1503 * @param int $countryID
1504 * @param string $field
1508 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1509 static $_cache = NULL;
1511 $cacheKey = "{$countryID}_{$field}";
1516 if (!empty($_cache[$cacheKey])) {
1517 return $_cache[$cacheKey];
1521 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1522 FROM civicrm_state_province
1523 WHERE country_id = %1
1532 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1535 while ($dao->fetch()) {
1536 $result[$dao->id
] = $dao->name
;
1539 // localise the stateProvince names if in an non-en_US locale
1540 $config = CRM_Core_Config
::singleton();
1541 $tsLocale = CRM_Core_I18n
::getLocale();
1542 if ($tsLocale != '' and $tsLocale != 'en_US') {
1543 $i18n = CRM_Core_I18n
::singleton();
1544 $i18n->localizeArray($result, array(
1545 'context' => 'province',
1547 $result = CRM_Utils_Array
::asort($result);
1550 $_cache[$cacheKey] = $result;
1552 CRM_Utils_Hook
::buildStateProvinceForCountry($countryID, $result);
1558 * @param int $stateID
1562 public static function &countyForState($stateID) {
1563 if (is_array($stateID)) {
1564 $states = implode(", ", $stateID);
1566 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1568 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1569 WHERE civicrm_county.state_province_id in ( $states )
1570 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1572 $dao = CRM_Core_DAO
::executeQuery($query);
1575 while ($dao->fetch()) {
1576 $result[$dao->id
] = $dao->abbreviation
. ': ' . $dao->name
;
1581 static $_cache = NULL;
1583 $cacheKey = "{$stateID}_name";
1588 if (!empty($_cache[$cacheKey])) {
1589 return $_cache[$cacheKey];
1593 SELECT civicrm_county.name name, civicrm_county.id id
1595 WHERE state_province_id = %1
1604 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1607 while ($dao->fetch()) {
1608 $result[$dao->id
] = $dao->name
;
1616 * Given a state ID return the country ID, this allows
1617 * us to populate forms and values for downstream code
1619 * @param int $stateID
1622 * the country id that the state belongs to
1624 public static function countryIDForStateID($stateID) {
1625 if (empty($stateID)) {
1626 return CRM_Core_DAO
::$_nullObject;
1631 FROM civicrm_state_province
1634 $params = array(1 => array($stateID, 'Integer'));
1636 return CRM_Core_DAO
::singleValueQuery($query, $params);
1640 * Get all types of Greetings.
1642 * The static array of greeting is returned
1646 * Get All Email Greetings - default is to get only active ones.
1648 * @param string $columnName
1651 * array reference of all greetings.
1653 public static function greeting($filter, $columnName = 'label') {
1654 $index = $filter['greeting_type'] . '_' . $columnName;
1656 // also add contactType to the array
1657 $contactType = CRM_Utils_Array
::value('contact_type', $filter);
1659 $index .= '_' . $contactType;
1662 if (NULL === self
::$greeting) {
1663 self
::$greeting = array();
1666 if (!CRM_Utils_Array
::value($index, self
::$greeting)) {
1667 $filterCondition = NULL;
1669 $filterVal = 'v.filter =';
1670 switch ($contactType) {
1679 case 'Organization':
1683 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1686 self
::$greeting[$index] = CRM_Core_OptionGroup
::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1689 return self
::$greeting[$index];
1693 * Construct array of default greeting values for contact type.
1697 * array reference of default greetings.
1699 public static function &greetingDefaults() {
1700 if (!self
::$greetingDefaults) {
1701 $defaultGreetings = array();
1702 $contactTypes = self
::get('CRM_Contact_DAO_Contact', 'contact_type', array(
1703 'keyColumn' => 'id',
1704 'labelColumn' => 'name',
1707 foreach ($contactTypes as $filter => $contactType) {
1708 $filterCondition = " AND (v.filter = 0 OR v.filter = $filter) AND v.is_default = 1 ";
1710 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1711 $tokenVal = CRM_Core_OptionGroup
::values($greeting, NULL, NULL, NULL, $filterCondition, 'label');
1712 $defaultGreetings[$contactType][$greeting] = $tokenVal;
1716 self
::$greetingDefaults = $defaultGreetings;
1719 return self
::$greetingDefaults;
1723 * Get all extensions.
1725 * The static array extensions
1727 * FIXME: This is called by civix but not by any core code. We
1728 * should provide an API call which civix can use instead.
1732 * array($fullyQualifiedName => $label) list of extensions
1734 public static function &getExtensions() {
1735 if (!self
::$extensions) {
1736 self
::$extensions = array();
1738 SELECT full_name, label
1739 FROM civicrm_extension
1742 $dao = CRM_Core_DAO
::executeQuery($sql);
1743 while ($dao->fetch()) {
1744 self
::$extensions[$dao->full_name
] = $dao->label
;
1748 return self
::$extensions;
1752 * Get all options values.
1754 * The static array option values is returned
1757 * @param bool $optionGroupName
1758 * Get All Option Group values- default is to get only active ones.
1761 * @param null $condition
1764 * array reference of all Option Group Name
1766 public static function accountOptionValues($optionGroupName, $id = NULL, $condition = NULL) {
1767 $cacheKey = $optionGroupName . '_' . $condition;
1768 if (empty(self
::$accountOptionValues[$cacheKey])) {
1769 self
::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup
::values($optionGroupName, FALSE, FALSE, FALSE, $condition);
1772 return CRM_Utils_Array
::value($id, self
::$accountOptionValues[$cacheKey]);
1775 return self
::$accountOptionValues[$cacheKey];
1779 * Fetch the list of active extensions of type 'module'
1781 * @param bool $fresh
1782 * Whether to forcibly reload extensions list from canonical store.
1785 * array(array('prefix' => $, 'file' => $))
1787 public static function getModuleExtensions($fresh = FALSE) {
1788 return CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles($fresh);
1793 * Get all tax rates.
1795 * The static array tax rates is returned
1798 * array list of tax rates with the financial type
1800 public static function getTaxRates() {
1801 if (!isset(Civi
::$statics[__CLASS__
]['taxRates'])) {
1802 Civi
::$statics[__CLASS__
]['taxRates'] = array();
1803 $option = civicrm_api3('option_value', 'get', array(
1805 'option_group_id' => 'account_relationship',
1806 'name' => 'Sales Tax Account is',
1809 if ($option['count'] !== 0) {
1810 if ($option['count'] > 1) {
1811 foreach ($option['values'] as $opt) {
1812 $value[] = $opt['value'];
1816 $value[] = $option['values'][0]['value'];
1818 $where = 'AND efa.account_relationship IN (' . implode(', ', $value) . ' )';
1824 SELECT fa.tax_rate, efa.entity_id
1825 FROM civicrm_entity_financial_account efa
1826 INNER JOIN civicrm_financial_account fa ON fa.id = efa.financial_account_id
1827 WHERE efa.entity_table = 'civicrm_financial_type'
1829 AND fa.is_active = 1";
1830 $dao = CRM_Core_DAO
::executeQuery($sql);
1831 while ($dao->fetch()) {
1832 Civi
::$statics[__CLASS__
]['taxRates'][$dao->entity_id
] = $dao->tax_rate
;
1836 return Civi
::$statics[__CLASS__
]['taxRates'];