3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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;
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 $groupIterator;
112 private static $relationshipType;
115 * Civicrm groups that are not smart groups
118 private static $staticGroup;
124 private static $currencyCode;
130 private static $paymentProcessor;
133 * Payment processor types
136 private static $paymentProcessorType;
142 private static $worldRegions;
145 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
150 private static $activityStatus;
156 private static $visibility;
162 private static $greeting;
168 private static $greetingDefaults;
171 * Extensions of type module
174 private static $extensions;
177 * Financial Account Type
180 private static $accountOptionValues;
186 private static $taxRates;
189 * Low-level option getter, rarely accessed directly.
190 * NOTE: Rather than calling this function directly use CRM_*_BAO_*::buildOptions()
191 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Pseudoconstant+%28option+list%29+Reference
193 * NOTE: If someone undertakes a refactoring of this, please consider the use-case of
194 * the Setting.getoptions API. There is no DAO/field, but it would be nice to use the
195 * same 'pseudoconstant' struct in *.settings.php. This means loosening the coupling
196 * between $field lookup and the $pseudoconstant evaluation.
198 * @param string $daoName
199 * @param string $fieldName
200 * @param array $params
201 * - name string name of the option group
202 * - flip boolean results are return in id => label format if false
203 * if true, the results are reversed
204 * - grouping boolean if true, return the value in 'grouping' column (currently unsupported for tables other than option_value)
205 * - localize boolean if true, localize the results before returning
206 * - condition string|array add condition(s) to the sql query - will be concatenated using 'AND'
207 * - keyColumn string the column to use for 'id'
208 * - labelColumn string the column to use for 'label'
209 * - orderColumn string the column to use for sorting, defaults to 'weight' column if one exists, else defaults to labelColumn
210 * - onlyActive boolean return only the action option values
211 * - fresh boolean ignore cache entries and go back to DB
212 * @param string $context : Context string
215 * array on success, FALSE on error.
218 public static function get($daoName, $fieldName, $params = array(), $context = NULL) {
219 CRM_Core_DAO
::buildOptionsContext($context);
220 $flip = !empty($params['flip']);
221 // Merge params with defaults
225 'onlyActive' => ($context == 'validate' ||
$context == 'get') ?
FALSE : TRUE,
229 // Custom fields are not in the schema
230 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
231 $customField = new CRM_Core_DAO_CustomField();
232 $customField->id
= (int) substr($fieldName, 7);
233 $customField->find(TRUE);
236 if (!empty($customField->option_group_id
)) {
237 $options = CRM_Core_OptionGroup
::valuesByID($customField->option_group_id
,
241 // Note: for custom fields the 'name' column is NULL
242 CRM_Utils_Array
::value('labelColumn', $params, 'label'),
243 $params['onlyActive'],
248 if ($customField->data_type
=== 'StateProvince') {
249 $options = self
::stateProvince();
251 elseif ($customField->data_type
=== 'Country') {
252 $options = $context == 'validate' ? self
::countryIsoCode() : self
::country();
254 elseif ($customField->data_type
=== 'Boolean') {
255 $options = $context == 'validate' ?
array(0, 1) : CRM_Core_SelectValues
::boolean();
258 CRM_Utils_Hook
::customFieldOptions($customField->id
, $options, FALSE);
259 if ($options && $flip) {
260 $options = array_flip($options);
262 $customField->free();
266 // Core field: load schema
267 $dao = new $daoName();
268 $fieldSpec = $dao->getFieldSpec($fieldName);
270 // If neither worked then this field doesn't exist. Return false.
271 if (empty($fieldSpec)) {
275 elseif (!empty($fieldSpec['pseudoconstant'])) {
276 $pseudoconstant = $fieldSpec['pseudoconstant'];
278 // if callback is specified..
279 if (!empty($pseudoconstant['callback'])) {
280 return call_user_func(Civi\Core\Resolver
::singleton()->get($pseudoconstant['callback']));
283 // Merge params with schema defaults
285 'condition' => CRM_Utils_Array
::value('condition', $pseudoconstant, array()),
286 'keyColumn' => CRM_Utils_Array
::value('keyColumn', $pseudoconstant),
287 'labelColumn' => CRM_Utils_Array
::value('labelColumn', $pseudoconstant),
290 if ($context == 'abbreviate') {
291 switch ($fieldName) {
292 case 'state_province_id':
293 $params['labelColumn'] = 'abbreviation';
297 $params['labelColumn'] = 'iso_code';
304 // Fetch option group from option_value table
305 if (!empty($pseudoconstant['optionGroupName'])) {
306 if ($context == 'validate') {
307 $params['labelColumn'] = 'name';
309 if ($context == 'match') {
310 $params['keyColumn'] = 'name';
312 // Call our generic fn for retrieving from the option_value table
313 return CRM_Core_OptionGroup
::values(
314 $pseudoconstant['optionGroupName'],
318 $params['condition'] ?
' AND ' . implode(' AND ', (array) $params['condition']) : NULL,
319 $params['labelColumn'] ?
$params['labelColumn'] : 'label',
320 $params['onlyActive'],
322 $params['keyColumn'] ?
$params['keyColumn'] : 'value'
326 // Fetch options from other tables
327 if (!empty($pseudoconstant['table'])) {
328 // Normalize params so the serialized cache string will be consistent.
329 CRM_Utils_Array
::remove($params, 'flip', 'fresh');
331 $cacheKey = $daoName . $fieldName . serialize($params);
333 // Retrieve cached options
334 if (isset(self
::$cache[$cacheKey]) && empty($params['fresh'])) {
335 $output = self
::$cache[$cacheKey];
338 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($pseudoconstant['table']);
339 if (!class_exists($daoName)) {
342 // Get list of fields for the option table
343 $dao = new $daoName();
344 $availableFields = array_keys($dao->fieldKeys());
347 $select = "SELECT %1 AS id, %2 AS label";
350 $order = "ORDER BY %2";
352 // Use machine name in certain contexts
353 if ($context == 'validate' ||
$context == 'match') {
354 $nameField = $context == 'validate' ?
'labelColumn' : 'keyColumn';
355 if (!empty($pseudoconstant['nameColumn'])) {
356 $params[$nameField] = $pseudoconstant['nameColumn'];
358 elseif (in_array('name', $availableFields)) {
359 $params[$nameField] = 'name';
362 // Condition param can be passed as an sql clause string or an array of clauses
363 if (!empty($params['condition'])) {
364 $wheres[] = implode(' AND ', (array) $params['condition']);
366 // onlyActive param will automatically filter on common flags
367 if (!empty($params['onlyActive'])) {
368 foreach (array('is_active' => 1, 'is_deleted' => 0, 'is_test' => 0, 'is_hidden' => 0) as $flag => $val) {
369 if (in_array($flag, $availableFields)) {
370 $wheres[] = "$flag = $val";
374 // Filter domain specific options
375 if (in_array('domain_id', $availableFields)) {
376 $wheres[] = 'domain_id = ' . CRM_Core_Config
::domainID();
378 $queryParams = array(
379 1 => array($params['keyColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
380 2 => array($params['labelColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
381 3 => array($pseudoconstant['table'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
383 // Add orderColumn param
384 if (!empty($params['orderColumn'])) {
385 $queryParams[4] = array($params['orderColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
);
386 $order = "ORDER BY %4";
388 // Support no sorting if $params[orderColumn] is FALSE
389 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
392 // Default to 'weight' if that column exists
393 elseif (in_array('weight', $availableFields)) {
394 $order = "ORDER BY weight";
398 $query = "$select $from";
400 $query .= " WHERE " . implode($wheres, ' AND ');
402 $query .= ' ' . $order;
403 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
404 while ($dao->fetch()) {
405 $output[$dao->id
] = $dao->label
;
409 if (!empty($params['localize']) ||
$pseudoconstant['table'] == 'civicrm_country' ||
$pseudoconstant['table'] == 'civicrm_state_province') {
410 $I18nParams = array();
411 if ($pseudoconstant['table'] == 'civicrm_country') {
412 $I18nParams['context'] = 'country';
414 if ($pseudoconstant['table'] == 'civicrm_state_province') {
415 $I18nParams['context'] = 'province';
417 $i18n = CRM_Core_I18n
::singleton();
418 $i18n->localizeArray($output, $I18nParams);
419 // Maintain sort by label
420 if ($order == "ORDER BY %2") {
421 CRM_Utils_Array
::asort($output);
424 self
::$cache[$cacheKey] = $output;
426 return $flip ?
array_flip($output) : $output;
430 // Return "Yes" and "No" for boolean fields
431 elseif (CRM_Utils_Array
::value('type', $fieldSpec) === CRM_Utils_Type
::T_BOOLEAN
) {
432 $output = $context == 'validate' ?
array(0, 1) : array(1 => ts('Yes'), 0 => ts('No'));
433 return $flip ?
array_flip($output) : $output;
435 // If we're still here, it's an error. Return FALSE.
440 * Fetch the translated label for a field given its key.
442 * @param string $baoName
443 * @param string $fieldName
444 * @param string|Int $key
446 * TODO: Accept multivalued input?
448 * @return bool|null|string
449 * FALSE if the given field has no associated option list
450 * NULL if the given key has no corresponding option
451 * String if label is found
453 public static function getLabel($baoName, $fieldName, $key) {
454 $values = $baoName::buildOptions($fieldName, 'get');
455 if ($values === FALSE) {
458 return CRM_Utils_Array
::value($key, $values);
462 * Fetch the machine name for a field given its key.
464 * @param string $baoName
465 * @param string $fieldName
466 * @param string|Int $key
468 * @return bool|null|string
469 * FALSE if the given field has no associated option list
470 * NULL if the given key has no corresponding option
471 * String if label is found
473 public static function getName($baoName, $fieldName, $key) {
474 $values = $baoName::buildOptions($fieldName, 'validate');
475 if ($values === FALSE) {
478 return CRM_Utils_Array
::value($key, $values);
482 * Fetch the key for a field option given its name.
484 * @param string $baoName
485 * @param string $fieldName
486 * @param string|Int $value
488 * @return bool|null|string|int
489 * FALSE if the given field has no associated option list
490 * NULL if the given key has no corresponding option
491 * String|Number if key is found
493 public static function getKey($baoName, $fieldName, $value) {
494 $values = $baoName::buildOptions($fieldName, 'validate');
495 if ($values === FALSE) {
498 return CRM_Utils_Array
::key($value, $values);
502 * Lookup the admin page at which a field's option list can be edited
504 * @return string|null
506 public static function getOptionEditUrl($fieldSpec) {
507 // If it's an option group, that's easy
508 if (!empty($fieldSpec['pseudoconstant']['optionGroupName'])) {
509 return 'civicrm/admin/options/' . $fieldSpec['pseudoconstant']['optionGroupName'];
511 // For everything else...
512 elseif (!empty($fieldSpec['pseudoconstant']['table'])) {
513 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($fieldSpec['pseudoconstant']['table']);
517 // We don't have good mapping so have to do a bit of guesswork from the menu
518 list(, $parent, , $child) = explode('_', $daoName);
519 $sql = "SELECT path FROM civicrm_menu
520 WHERE page_callback LIKE '%CRM_Admin_Page_$child%' OR page_callback LIKE '%CRM_{$parent}_Page_$child%'
521 ORDER BY page_callback
523 return CRM_Core_Dao
::singleValueQuery($sql);
529 * DEPRECATED generic populate method.
530 * All pseudoconstant functions that use this method are also @deprecated
532 * The static array $var is populated from the db
533 * using the <b>$name DAO</b>.
535 * Note: any database errors will be trapped by the DAO.
538 * The associative array we will fill.
539 * @param string $name
540 * The name of the DAO.
542 * Get all objects. default is to get only active ones.
543 * @param string $retrieve
544 * The field that we are interested in (normally name, differs in some objects).
545 * @param string $filter
546 * The field that we want to filter the result set with.
547 * @param string $condition
548 * The condition that gets passed to the final query as the WHERE clause.
550 * @param bool $orderby
556 public static function populate(
561 $filter = 'is_active',
567 $cacheKey = "CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}";
568 $cache = CRM_Utils_Cache
::singleton();
569 $var = $cache->get($cacheKey);
570 if ($var && empty($force)) {
574 $object = new $name();
576 $object->selectAdd();
577 $object->selectAdd("$key, $retrieve");
579 $object->whereAdd($condition);
583 $object->orderBy($retrieve);
586 $object->orderBy($orderby);
590 $object->$filter = 1;
595 while ($object->fetch()) {
596 $var[$object->$key] = $object->$retrieve;
599 $cache->set($cacheKey, $var);
603 * Flush given pseudoconstant so it can be reread from db.
604 * nex time it's requested.
607 * @param bool|string $name pseudoconstant to be flushed
609 public static function flush($name = 'cache') {
610 if (isset(self
::$
$name)) {
613 if ($name == 'cache') {
614 CRM_Core_OptionGroup
::flushAll();
619 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
621 * Get all Activty types.
623 * The static array activityType is returned
627 * array reference of all activity types.
629 public static function &activityType() {
630 $args = func_get_args();
631 $all = CRM_Utils_Array
::value(0, $args, TRUE);
632 $includeCaseActivities = CRM_Utils_Array
::value(1, $args, FALSE);
633 $reset = CRM_Utils_Array
::value(2, $args, FALSE);
634 $returnColumn = CRM_Utils_Array
::value(3, $args, 'label');
635 $includeCampaignActivities = CRM_Utils_Array
::value(4, $args, FALSE);
636 $onlyComponentActivities = CRM_Utils_Array
::value(5, $args, FALSE);
637 $index = (int) $all . '_' . $returnColumn . '_' . (int) $includeCaseActivities;
638 $index .= '_' . (int) $includeCampaignActivities;
639 $index .= '_' . (int) $onlyComponentActivities;
641 if (NULL === self
::$activityType) {
642 self
::$activityType = array();
645 if (!isset(self
::$activityType[$index]) ||
$reset) {
648 $condition = 'AND filter = 0';
650 $componentClause = " v.component_id IS NULL";
651 if ($onlyComponentActivities) {
652 $componentClause = " v.component_id IS NOT NULL";
655 $componentIds = array();
656 $compInfo = CRM_Core_Component
::getEnabledComponents();
658 // build filter for listing activity types only if their
659 // respective components are enabled
660 foreach ($compInfo as $compName => $compObj) {
661 if ($compName == 'CiviCase') {
662 if ($includeCaseActivities) {
663 $componentIds[] = $compObj->componentID
;
666 elseif ($compName == 'CiviCampaign') {
667 if ($includeCampaignActivities) {
668 $componentIds[] = $compObj->componentID
;
672 $componentIds[] = $compObj->componentID
;
676 if (count($componentIds)) {
677 $componentIds = implode(',', $componentIds);
678 $componentClause = " ($componentClause OR v.component_id IN ($componentIds))";
679 if ($onlyComponentActivities) {
680 $componentClause = " ( v.component_id IN ($componentIds ) )";
683 $condition = $condition . ' AND ' . $componentClause;
685 self
::$activityType[$index] = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
687 return self
::$activityType[$index];
691 * Get all the State/Province from database.
693 * The static array stateProvince is returned, and if it's
694 * called the first time, the <b>State Province DAO</b> is used
695 * to get all the States.
697 * Note: any database errors will be trapped by the DAO.
700 * @param bool|int $id - Optional id to return
705 * array reference of all State/Provinces.
707 public static function &stateProvince($id = FALSE, $limit = TRUE) {
708 if (($id && !CRM_Utils_Array
::value($id, self
::$stateProvince)) ||
!self
::$stateProvince ||
!$id) {
709 $whereClause = FALSE;
711 $countryIsoCodes = self
::countryIsoCode();
712 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
714 foreach ($limitCodes as $code) {
715 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
717 if (!empty($limitIds)) {
718 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
721 $whereClause = FALSE;
724 self
::populate(self
::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
726 // localise the province names if in an non-en_US locale
728 if ($tsLocale != '' and $tsLocale != 'en_US') {
729 $i18n = CRM_Core_I18n
::singleton();
730 $i18n->localizeArray(self
::$stateProvince, array(
731 'context' => 'province',
733 self
::$stateProvince = CRM_Utils_Array
::asort(self
::$stateProvince);
737 if (array_key_exists($id, self
::$stateProvince)) {
738 return self
::$stateProvince[$id];
745 return self
::$stateProvince;
749 * Get all the State/Province abbreviations from the database.
751 * Same as above, except gets the abbreviations instead of the names.
754 * @param bool|int $id - Optional id to return
759 * array reference of all State/Province abbreviations.
761 public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
765 FROM civicrm_state_province
773 return CRM_Core_DAO
::singleValueQuery($query, $params);
776 if (!self
::$stateProvinceAbbreviation ||
!$id) {
778 $whereClause = FALSE;
781 $countryIsoCodes = self
::countryIsoCode();
782 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
784 foreach ($limitCodes as $code) {
785 $tmpArray = array_keys($countryIsoCodes, $code);
787 if (!empty($tmpArray)) {
788 $limitIds[] = array_shift($tmpArray);
791 if (!empty($limitIds)) {
792 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
795 self
::populate(self
::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
799 if (array_key_exists($id, self
::$stateProvinceAbbreviation)) {
800 return self
::$stateProvinceAbbreviation[$id];
807 return self
::$stateProvinceAbbreviation;
811 * Get all the countries from database.
813 * The static array country is returned, and if it's
814 * called the first time, the <b>Country DAO</b> is used
815 * to get all the countries.
817 * Note: any database errors will be trapped by the DAO.
820 * @param bool|int $id - Optional id to return
822 * @param bool $applyLimit
825 * array reference of all countries.
827 public static function country($id = FALSE, $applyLimit = TRUE) {
828 if (($id && !CRM_Utils_Array
::value($id, self
::$country)) ||
!self
::$country ||
!$id) {
830 $config = CRM_Core_Config
::singleton();
831 $limitCodes = array();
834 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
835 // (ensuring it's a subset of the legal values)
836 // K/P: We need to fix this, i dont think it works with new setting files
837 $limitCodes = CRM_Core_BAO_Country
::countryLimit();
838 if (!is_array($limitCodes)) {
840 $config->countryLimit
=> 1,
844 $limitCodes = array_intersect(self
::countryIsoCode(), $limitCodes);
847 if (count($limitCodes)) {
848 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
854 self
::populate(self
::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
856 // if default country is set, percolate it to the top
857 if ($config->defaultContactCountry()) {
858 $countryIsoCodes = self
::countryIsoCode();
859 $defaultID = array_search($config->defaultContactCountry(), $countryIsoCodes);
860 if ($defaultID !== FALSE) {
861 $default[$defaultID] = CRM_Utils_Array
::value($defaultID, self
::$country);
862 self
::$country = $default + self
::$country;
866 // localise the country names if in an non-en_US locale
868 if ($tsLocale != '' and $tsLocale != 'en_US') {
869 $i18n = CRM_Core_I18n
::singleton();
870 $i18n->localizeArray(self
::$country, array(
871 'context' => 'country',
873 self
::$country = CRM_Utils_Array
::asort(self
::$country);
877 if (array_key_exists($id, self
::$country)) {
878 return self
::$country[$id];
881 return CRM_Core_DAO
::$_nullObject;
884 return self
::$country;
888 * Get all the country ISO Code abbreviations from the database.
890 * The static array countryIsoCode is returned, and if it's
891 * called the first time, the <b>Country DAO</b> is used
892 * to get all the countries' ISO codes.
894 * Note: any database errors will be trapped by the DAO.
900 * array reference of all country ISO codes.
902 public static function &countryIsoCode($id = FALSE) {
903 if (!self
::$countryIsoCode) {
904 self
::populate(self
::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
907 if (array_key_exists($id, self
::$countryIsoCode)) {
908 return self
::$countryIsoCode[$id];
911 return CRM_Core_DAO
::$_nullObject;
914 return self
::$countryIsoCode;
918 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
920 * Get all groups from database
922 * The static array group is returned, and if it's
923 * called the first time, the <b>Group DAO</b> is used
924 * to get all the groups.
926 * Note: any database errors will be trapped by the DAO.
928 * @param string $groupType
929 * Type of group(Access/Mailing).
930 * @param bool $excludeHidden
931 * Exclude hidden groups.
935 * array reference of all groups.
937 public static function allGroup($groupType = NULL, $excludeHidden = TRUE) {
938 $condition = CRM_Contact_BAO_Group
::groupTypeCondition($groupType, $excludeHidden);
941 self
::$group = array();
944 $groupKey = ($groupType ?
$groupType : 'null') . !empty($excludeHidden);
946 if (!isset(self
::$group[$groupKey])) {
947 self
::$group[$groupKey] = NULL;
948 self
::populate(self
::$group[$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
950 return self
::$group[$groupKey];
954 * Create or get groups iterator (iterates over nested groups in a
957 * The GroupNesting instance is returned; it's created if this is being
958 * called for the first time
962 * @param bool $styledLabels
964 * @return CRM_Contact_BAO_GroupNesting
966 public static function &groupIterator($styledLabels = FALSE) {
967 if (!self
::$groupIterator) {
968 // When used as an object, GroupNesting implements Iterator
969 // and iterates nested groups in a logical manner for us
970 self
::$groupIterator = new CRM_Contact_BAO_GroupNesting($styledLabels);
972 return self
::$groupIterator;
976 * Get all permissioned groups from database.
978 * The static array group is returned, and if it's
979 * called the first time, the <b>Group DAO</b> is used
980 * to get all the groups.
982 * Note: any database errors will be trapped by the DAO.
984 * @param string $groupType
985 * Type of group(Access/Mailing).
986 * @param bool $excludeHidden
987 * Exclude hidden groups.
991 * array reference of all groups.
993 public static function group($groupType = NULL, $excludeHidden = TRUE) {
994 return CRM_Core_Permission
::group($groupType, $excludeHidden);
998 * Fetch groups in a nested format suitable for use in select form element.
999 * @param bool $checkPermissions
1000 * @param string|null $groupType
1001 * @param bool $excludeHidden
1004 public static function nestedGroup($checkPermissions = TRUE, $groupType = NULL, $excludeHidden = TRUE) {
1005 $groups = $checkPermissions ? self
::group($groupType, $excludeHidden) : self
::allGroup($groupType, $excludeHidden);
1006 return CRM_Contact_BAO_Group
::getGroupsHierarchy($groups, NULL, ' ', TRUE);
1010 * Get all permissioned groups from database.
1012 * The static array group is returned, and if it's
1013 * called the first time, the <b>Group DAO</b> is used
1014 * to get all the groups.
1016 * Note: any database errors will be trapped by the DAO.
1019 * @param bool $onlyPublic
1020 * @param null $groupType
1021 * @param bool $excludeHidden
1024 * array reference of all groups.
1026 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
1027 if (!self
::$staticGroup) {
1028 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
1030 $condition .= " AND visibility != 'User and User Admin Only'";
1034 $condition .= ' AND ' . CRM_Contact_BAO_Group
::groupTypeCondition($groupType);
1037 if ($excludeHidden) {
1038 $condition .= ' AND is_hidden != 1 ';
1041 self
::populate(self
::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
1044 return self
::$staticGroup;
1048 * Get all Relationship Types from database.
1050 * The static array group is returned, and if it's
1051 * called the first time, the <b>RelationshipType DAO</b> is used
1052 * to get all the relationship types.
1054 * Note: any database errors will be trapped by the DAO.
1056 * @param string $valueColumnName
1057 * Db column name/label.
1058 * @param bool $reset
1059 * Reset relationship types if true.
1063 * array reference of all relationship types.
1065 public static function &relationshipType($valueColumnName = 'label', $reset = FALSE) {
1066 if (!CRM_Utils_Array
::value($valueColumnName, self
::$relationshipType) ||
$reset) {
1067 self
::$relationshipType[$valueColumnName] = array();
1069 //now we have name/label columns CRM-3336
1070 $column_a_b = "{$valueColumnName}_a_b";
1071 $column_b_a = "{$valueColumnName}_b_a";
1073 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1074 $relationshipTypeDAO->selectAdd();
1075 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1076 $relationshipTypeDAO->is_active
= 1;
1077 $relationshipTypeDAO->find();
1078 while ($relationshipTypeDAO->fetch()) {
1080 self
::$relationshipType[$valueColumnName][$relationshipTypeDAO->id
] = array(
1081 'id' => $relationshipTypeDAO->id
,
1082 $column_a_b => $relationshipTypeDAO->$column_a_b,
1083 $column_b_a => $relationshipTypeDAO->$column_b_a,
1084 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1085 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1086 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1087 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1092 return self
::$relationshipType[$valueColumnName];
1096 * Get all the ISO 4217 currency codes
1098 * so far, we use this for validation only, so there's no point of putting this into the database
1102 * array reference of all currency codes
1104 public static function ¤cyCode() {
1105 if (!self
::$currencyCode) {
1106 self
::$currencyCode = array(
1376 return self
::$currencyCode;
1380 * Get all the County from database.
1382 * The static array county is returned, and if it's
1383 * called the first time, the <b>County DAO</b> is used
1384 * to get all the Counties.
1386 * Note: any database errors will be trapped by the DAO.
1389 * @param bool|int $id - Optional id to return
1392 * array reference of all Counties
1394 public static function &county($id = FALSE) {
1395 if (!self
::$county) {
1397 $config = CRM_Core_Config
::singleton();
1398 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1399 self
::populate(self
::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1402 if (array_key_exists($id, self
::$county)) {
1403 return self
::$county[$id];
1406 return CRM_Core_DAO
::$_nullObject;
1409 return self
::$county;
1413 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1414 * Get all active payment processors
1416 * The static array paymentProcessor is returned
1420 * Get payment processors - default is to get only active ones.
1422 * Get test payment processors.
1424 * @param null $additionalCond
1427 * array of all payment processors
1429 public static function paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1430 $condition = "is_test = ";
1431 $condition .= ($test) ?
'1' : '0';
1433 if ($additionalCond) {
1434 $condition .= " AND ( $additionalCond ) ";
1437 // CRM-7178. Make sure we only include payment processors valid in this
1439 $condition .= " AND domain_id = " . CRM_Core_Config
::domainID();
1441 $cacheKey = $condition . '_' . (int) $all;
1442 if (!isset(self
::$paymentProcessor[$cacheKey])) {
1443 self
::populate(self
::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1446 return self
::$paymentProcessor[$cacheKey];
1450 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1452 * The static array paymentProcessorType is returned
1456 * Get payment processors - default is to get only active ones.
1459 * @param string $return
1462 * array of all payment processor types
1464 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1465 $cacheKey = $id . '_' . $return;
1466 if (empty(self
::$paymentProcessorType[$cacheKey])) {
1467 self
::populate(self
::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1469 if ($id && CRM_Utils_Array
::value($id, self
::$paymentProcessorType[$cacheKey])) {
1470 return self
::$paymentProcessorType[$cacheKey][$id];
1472 return self
::$paymentProcessorType[$cacheKey];
1476 * Get all the World Regions from Database.
1482 * array reference of all World Regions
1484 public static function &worldRegion($id = FALSE) {
1485 if (!self
::$worldRegions) {
1486 self
::populate(self
::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1490 if (array_key_exists($id, self
::$worldRegions)) {
1491 return self
::$worldRegions[$id];
1494 return CRM_Core_DAO
::$_nullObject;
1498 return self
::$worldRegions;
1502 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1504 * Get all Activity Statuses.
1506 * The static array activityStatus is returned
1509 * @param string $column
1512 * array reference of all activity statuses
1514 public static function &activityStatus($column = 'label') {
1515 if (NULL === self
::$activityStatus) {
1516 self
::$activityStatus = array();
1518 if (!array_key_exists($column, self
::$activityStatus)) {
1519 self
::$activityStatus[$column] = array();
1521 self
::$activityStatus[$column] = CRM_Core_OptionGroup
::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1524 return self
::$activityStatus[$column];
1528 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1530 * Get all Visibility levels.
1532 * The static array visibility is returned
1535 * @param string $column
1538 * array reference of all Visibility levels.
1540 public static function &visibility($column = 'label') {
1541 if (!isset(self
::$visibility)) {
1542 self
::$visibility = array();
1545 if (!isset(self
::$visibility[$column])) {
1546 self
::$visibility[$column] = CRM_Core_OptionGroup
::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1549 return self
::$visibility[$column];
1553 * @param int $countryID
1554 * @param string $field
1558 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1559 static $_cache = NULL;
1561 $cacheKey = "{$countryID}_{$field}";
1566 if (!empty($_cache[$cacheKey])) {
1567 return $_cache[$cacheKey];
1571 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1572 FROM civicrm_state_province
1573 WHERE country_id = %1
1582 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1585 while ($dao->fetch()) {
1586 $result[$dao->id
] = $dao->name
;
1589 // localise the stateProvince names if in an non-en_US locale
1590 $config = CRM_Core_Config
::singleton();
1592 if ($tsLocale != '' and $tsLocale != 'en_US') {
1593 $i18n = CRM_Core_I18n
::singleton();
1594 $i18n->localizeArray($result, array(
1595 'context' => 'province',
1597 $result = CRM_Utils_Array
::asort($result);
1600 $_cache[$cacheKey] = $result;
1602 CRM_Utils_Hook
::buildStateProvinceForCountry($countryID, $result);
1608 * @param int $stateID
1612 public static function &countyForState($stateID) {
1613 if (is_array($stateID)) {
1614 $states = implode(", ", $stateID);
1616 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1618 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1619 WHERE civicrm_county.state_province_id in ( $states )
1620 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1622 $dao = CRM_Core_DAO
::executeQuery($query);
1625 while ($dao->fetch()) {
1626 $result[$dao->id
] = $dao->abbreviation
. ': ' . $dao->name
;
1631 static $_cache = NULL;
1633 $cacheKey = "{$stateID}_name";
1638 if (!empty($_cache[$cacheKey])) {
1639 return $_cache[$cacheKey];
1643 SELECT civicrm_county.name name, civicrm_county.id id
1645 WHERE state_province_id = %1
1654 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1657 while ($dao->fetch()) {
1658 $result[$dao->id
] = $dao->name
;
1666 * Given a state ID return the country ID, this allows
1667 * us to populate forms and values for downstream code
1669 * @param int $stateID
1672 * the country id that the state belongs to
1674 public static function countryIDForStateID($stateID) {
1675 if (empty($stateID)) {
1676 return CRM_Core_DAO
::$_nullObject;
1681 FROM civicrm_state_province
1684 $params = array(1 => array($stateID, 'Integer'));
1686 return CRM_Core_DAO
::singleValueQuery($query, $params);
1690 * Get all types of Greetings.
1692 * The static array of greeting is returned
1696 * Get All Email Greetings - default is to get only active ones.
1698 * @param string $columnName
1701 * array reference of all greetings.
1703 public static function greeting($filter, $columnName = 'label') {
1704 $index = $filter['greeting_type'] . '_' . $columnName;
1706 // also add contactType to the array
1707 $contactType = CRM_Utils_Array
::value('contact_type', $filter);
1709 $index .= '_' . $contactType;
1712 if (NULL === self
::$greeting) {
1713 self
::$greeting = array();
1716 if (!CRM_Utils_Array
::value($index, self
::$greeting)) {
1717 $filterCondition = NULL;
1719 $filterVal = 'v.filter =';
1720 switch ($contactType) {
1729 case 'Organization':
1733 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1736 self
::$greeting[$index] = CRM_Core_OptionGroup
::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1739 return self
::$greeting[$index];
1743 * Construct array of default greeting values for contact type.
1747 * array reference of default greetings.
1749 public static function &greetingDefaults() {
1750 if (!self
::$greetingDefaults) {
1751 $defaultGreetings = array();
1752 $contactTypes = self
::get('CRM_Contact_DAO_Contact', 'contact_type', array(
1753 'keyColumn' => 'id',
1754 'labelColumn' => 'name',
1757 foreach ($contactTypes as $filter => $contactType) {
1758 $filterCondition = " AND (v.filter = 0 OR v.filter = $filter) AND v.is_default = 1 ";
1760 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1761 $tokenVal = CRM_Core_OptionGroup
::values($greeting, NULL, NULL, NULL, $filterCondition, 'label');
1762 $defaultGreetings[$contactType][$greeting] = $tokenVal;
1766 self
::$greetingDefaults = $defaultGreetings;
1769 return self
::$greetingDefaults;
1773 * Get all extensions.
1775 * The static array extensions
1777 * FIXME: This is called by civix but not by any core code. We
1778 * should provide an API call which civix can use instead.
1782 * array($fullyQualifiedName => $label) list of extensions
1784 public static function &getExtensions() {
1785 if (!self
::$extensions) {
1786 self
::$extensions = array();
1788 SELECT full_name, label
1789 FROM civicrm_extension
1792 $dao = CRM_Core_DAO
::executeQuery($sql);
1793 while ($dao->fetch()) {
1794 self
::$extensions[$dao->full_name
] = $dao->label
;
1798 return self
::$extensions;
1802 * Get all options values.
1804 * The static array option values is returned
1807 * @param bool $optionGroupName
1808 * Get All Option Group values- default is to get only active ones.
1811 * @param null $condition
1814 * array reference of all Option Group Name
1816 public static function accountOptionValues($optionGroupName, $id = NULL, $condition = NULL) {
1817 $cacheKey = $optionGroupName . '_' . $condition;
1818 if (empty(self
::$accountOptionValues[$cacheKey])) {
1819 self
::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup
::values($optionGroupName, FALSE, FALSE, FALSE, $condition);
1822 return CRM_Utils_Array
::value($id, self
::$accountOptionValues[$cacheKey]);
1825 return self
::$accountOptionValues[$cacheKey];
1829 * Fetch the list of active extensions of type 'module'
1831 * @param bool $fresh
1832 * Whether to forcibly reload extensions list from canonical store.
1835 * array(array('prefix' => $, 'file' => $))
1837 public static function getModuleExtensions($fresh = FALSE) {
1838 return CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles($fresh);
1843 * Get all tax rates.
1845 * The static array tax rates is returned
1848 * array list of tax rates with the financial type
1850 public static function getTaxRates() {
1851 if (!self
::$taxRates) {
1852 self
::$taxRates = array();
1854 SELECT fa.tax_rate, efa.entity_id
1855 FROM civicrm_entity_financial_account efa
1856 INNER JOIN civicrm_financial_account fa ON fa.id = efa.financial_account_id
1857 INNER JOIN civicrm_option_value cov ON cov.value = efa.account_relationship
1858 INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id
1859 WHERE efa.entity_table = 'civicrm_financial_type'
1860 AND cov.name = 'Sales Tax Account is'
1861 AND cog.name = 'account_relationship'
1862 AND fa.is_active = 1";
1863 $dao = CRM_Core_DAO
::executeQuery($sql);
1864 while ($dao->fetch()) {
1865 self
::$taxRates[$dao->entity_id
] = $dao->tax_rate
;
1869 return self
::$taxRates;