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;
710 $config = CRM_Core_Config
::singleton();
712 $countryIsoCodes = self
::countryIsoCode();
713 $limitCodes = $config->provinceLimit();
715 foreach ($limitCodes as $code) {
716 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
718 if (!empty($limitIds)) {
719 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
722 $whereClause = FALSE;
725 self
::populate(self
::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
727 // localise the province names if in an non-en_US locale
729 if ($tsLocale != '' and $tsLocale != 'en_US') {
730 $i18n = CRM_Core_I18n
::singleton();
731 $i18n->localizeArray(self
::$stateProvince, array(
732 'context' => 'province',
734 self
::$stateProvince = CRM_Utils_Array
::asort(self
::$stateProvince);
738 if (array_key_exists($id, self
::$stateProvince)) {
739 return self
::$stateProvince[$id];
746 return self
::$stateProvince;
750 * Get all the State/Province abbreviations from the database.
752 * Same as above, except gets the abbreviations instead of the names.
755 * @param bool|int $id - Optional id to return
760 * array reference of all State/Province abbreviations.
762 public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
766 FROM civicrm_state_province
774 return CRM_Core_DAO
::singleValueQuery($query, $params);
777 if (!self
::$stateProvinceAbbreviation ||
!$id) {
779 $whereClause = FALSE;
782 $config = CRM_Core_Config
::singleton();
783 $countryIsoCodes = self
::countryIsoCode();
784 $limitCodes = $config->provinceLimit();
786 foreach ($limitCodes as $code) {
787 $tmpArray = array_keys($countryIsoCodes, $code);
789 if (!empty($tmpArray)) {
790 $limitIds[] = array_shift($tmpArray);
793 if (!empty($limitIds)) {
794 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
797 self
::populate(self
::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
801 if (array_key_exists($id, self
::$stateProvinceAbbreviation)) {
802 return self
::$stateProvinceAbbreviation[$id];
809 return self
::$stateProvinceAbbreviation;
813 * Get all the countries from database.
815 * The static array country is returned, and if it's
816 * called the first time, the <b>Country DAO</b> is used
817 * to get all the countries.
819 * Note: any database errors will be trapped by the DAO.
822 * @param bool|int $id - Optional id to return
824 * @param bool $applyLimit
827 * array reference of all countries.
829 public static function country($id = FALSE, $applyLimit = TRUE) {
830 if (($id && !CRM_Utils_Array
::value($id, self
::$country)) ||
!self
::$country ||
!$id) {
832 $config = CRM_Core_Config
::singleton();
833 $limitCodes = array();
836 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
837 // (ensuring it's a subset of the legal values)
838 // K/P: We need to fix this, i dont think it works with new setting files
839 $limitCodes = $config->countryLimit();
840 if (!is_array($limitCodes)) {
842 $config->countryLimit
=> 1,
846 $limitCodes = array_intersect(self
::countryIsoCode(), $limitCodes);
849 if (count($limitCodes)) {
850 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
856 self
::populate(self
::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
858 // if default country is set, percolate it to the top
859 if ($config->defaultContactCountry()) {
860 $countryIsoCodes = self
::countryIsoCode();
861 $defaultID = array_search($config->defaultContactCountry(), $countryIsoCodes);
862 if ($defaultID !== FALSE) {
863 $default[$defaultID] = CRM_Utils_Array
::value($defaultID, self
::$country);
864 self
::$country = $default + self
::$country;
868 // localise the country names if in an non-en_US locale
870 if ($tsLocale != '' and $tsLocale != 'en_US') {
871 $i18n = CRM_Core_I18n
::singleton();
872 $i18n->localizeArray(self
::$country, array(
873 'context' => 'country',
875 self
::$country = CRM_Utils_Array
::asort(self
::$country);
879 if (array_key_exists($id, self
::$country)) {
880 return self
::$country[$id];
883 return CRM_Core_DAO
::$_nullObject;
886 return self
::$country;
890 * Get all the country ISO Code abbreviations from the database.
892 * The static array countryIsoCode is returned, and if it's
893 * called the first time, the <b>Country DAO</b> is used
894 * to get all the countries' ISO codes.
896 * Note: any database errors will be trapped by the DAO.
902 * array reference of all country ISO codes.
904 public static function &countryIsoCode($id = FALSE) {
905 if (!self
::$countryIsoCode) {
906 self
::populate(self
::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
909 if (array_key_exists($id, self
::$countryIsoCode)) {
910 return self
::$countryIsoCode[$id];
913 return CRM_Core_DAO
::$_nullObject;
916 return self
::$countryIsoCode;
920 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
922 * Get all 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 &allGroup($groupType = NULL, $excludeHidden = TRUE) {
940 $condition = CRM_Contact_BAO_Group
::groupTypeCondition($groupType, $excludeHidden);
943 self
::$group = array();
946 $groupKey = $groupType ?
$groupType : 'null';
948 if (!isset(self
::$group[$groupKey])) {
949 self
::$group[$groupKey] = NULL;
950 self
::populate(self
::$group[$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
952 return self
::$group[$groupKey];
956 * Create or get groups iterator (iterates over nested groups in a
959 * The GroupNesting instance is returned; it's created if this is being
960 * called for the first time
964 * @param bool $styledLabels
966 * @return CRM_Contact_BAO_GroupNesting
968 public static function &groupIterator($styledLabels = FALSE) {
969 if (!self
::$groupIterator) {
970 // When used as an object, GroupNesting implements Iterator
971 // and iterates nested groups in a logical manner for us
972 self
::$groupIterator = new CRM_Contact_BAO_GroupNesting($styledLabels);
974 return self
::$groupIterator;
978 * Get all permissioned groups from database.
980 * The static array group is returned, and if it's
981 * called the first time, the <b>Group DAO</b> is used
982 * to get all the groups.
984 * Note: any database errors will be trapped by the DAO.
986 * @param string $groupType
987 * Type of group(Access/Mailing).
988 * @param bool $excludeHidden
989 * Exclude hidden groups.
993 * array reference of all groups.
995 public static function group($groupType = NULL, $excludeHidden = TRUE) {
996 return CRM_Core_Permission
::group($groupType, $excludeHidden);
1000 * Fetch groups in a nested format suitable for use in select form element.
1001 * @param bool $checkPermissions
1002 * @param string|null $groupType
1003 * @param bool $excludeHidden
1006 public static function nestedGroup($checkPermissions = TRUE, $groupType = NULL, $excludeHidden = TRUE) {
1007 $groups = $checkPermissions ? self
::group($groupType, $excludeHidden) : self
::allGroup($groupType, $excludeHidden);
1008 return CRM_Contact_BAO_Group
::getGroupsHierarchy($groups, NULL, ' ', TRUE);
1012 * Get all permissioned groups from database.
1014 * The static array group is returned, and if it's
1015 * called the first time, the <b>Group DAO</b> is used
1016 * to get all the groups.
1018 * Note: any database errors will be trapped by the DAO.
1021 * @param bool $onlyPublic
1022 * @param null $groupType
1023 * @param bool $excludeHidden
1026 * array reference of all groups.
1028 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
1029 if (!self
::$staticGroup) {
1030 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
1032 $condition .= " AND visibility != 'User and User Admin Only'";
1036 $condition .= ' AND ' . CRM_Contact_BAO_Group
::groupTypeCondition($groupType);
1039 if ($excludeHidden) {
1040 $condition .= ' AND is_hidden != 1 ';
1043 self
::populate(self
::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
1046 return self
::$staticGroup;
1050 * Get all Relationship Types from database.
1052 * The static array group is returned, and if it's
1053 * called the first time, the <b>RelationshipType DAO</b> is used
1054 * to get all the relationship types.
1056 * Note: any database errors will be trapped by the DAO.
1058 * @param string $valueColumnName
1059 * Db column name/label.
1060 * @param bool $reset
1061 * Reset relationship types if true.
1065 * array reference of all relationship types.
1067 public static function &relationshipType($valueColumnName = 'label', $reset = FALSE) {
1068 if (!CRM_Utils_Array
::value($valueColumnName, self
::$relationshipType) ||
$reset) {
1069 self
::$relationshipType[$valueColumnName] = array();
1071 //now we have name/label columns CRM-3336
1072 $column_a_b = "{$valueColumnName}_a_b";
1073 $column_b_a = "{$valueColumnName}_b_a";
1075 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1076 $relationshipTypeDAO->selectAdd();
1077 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1078 $relationshipTypeDAO->is_active
= 1;
1079 $relationshipTypeDAO->find();
1080 while ($relationshipTypeDAO->fetch()) {
1082 self
::$relationshipType[$valueColumnName][$relationshipTypeDAO->id
] = array(
1083 'id' => $relationshipTypeDAO->id
,
1084 $column_a_b => $relationshipTypeDAO->$column_a_b,
1085 $column_b_a => $relationshipTypeDAO->$column_b_a,
1086 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1087 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1088 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1089 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1094 return self
::$relationshipType[$valueColumnName];
1098 * Get all the ISO 4217 currency codes
1100 * so far, we use this for validation only, so there's no point of putting this into the database
1104 * array reference of all currency codes
1106 public static function ¤cyCode() {
1107 if (!self
::$currencyCode) {
1108 self
::$currencyCode = array(
1378 return self
::$currencyCode;
1382 * Get all the County from database.
1384 * The static array county is returned, and if it's
1385 * called the first time, the <b>County DAO</b> is used
1386 * to get all the Counties.
1388 * Note: any database errors will be trapped by the DAO.
1391 * @param bool|int $id - Optional id to return
1394 * array reference of all Counties
1396 public static function &county($id = FALSE) {
1397 if (!self
::$county) {
1399 $config = CRM_Core_Config
::singleton();
1400 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1401 self
::populate(self
::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1404 if (array_key_exists($id, self
::$county)) {
1405 return self
::$county[$id];
1408 return CRM_Core_DAO
::$_nullObject;
1411 return self
::$county;
1415 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1416 * Get all active payment processors
1418 * The static array paymentProcessor is returned
1422 * Get payment processors - default is to get only active ones.
1424 * Get test payment processors.
1426 * @param null $additionalCond
1429 * array of all payment processors
1431 public static function paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1432 $condition = "is_test = ";
1433 $condition .= ($test) ?
'1' : '0';
1435 if ($additionalCond) {
1436 $condition .= " AND ( $additionalCond ) ";
1439 // CRM-7178. Make sure we only include payment processors valid in this
1441 $condition .= " AND domain_id = " . CRM_Core_Config
::domainID();
1443 $cacheKey = $condition . '_' . (int) $all;
1444 if (!isset(self
::$paymentProcessor[$cacheKey])) {
1445 self
::populate(self
::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1448 return self
::$paymentProcessor[$cacheKey];
1452 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1454 * The static array paymentProcessorType is returned
1458 * Get payment processors - default is to get only active ones.
1461 * @param string $return
1464 * array of all payment processor types
1466 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1467 $cacheKey = $id . '_' . $return;
1468 if (empty(self
::$paymentProcessorType[$cacheKey])) {
1469 self
::populate(self
::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1471 if ($id && CRM_Utils_Array
::value($id, self
::$paymentProcessorType[$cacheKey])) {
1472 return self
::$paymentProcessorType[$cacheKey][$id];
1474 return self
::$paymentProcessorType[$cacheKey];
1478 * Get all the World Regions from Database.
1484 * array reference of all World Regions
1486 public static function &worldRegion($id = FALSE) {
1487 if (!self
::$worldRegions) {
1488 self
::populate(self
::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1492 if (array_key_exists($id, self
::$worldRegions)) {
1493 return self
::$worldRegions[$id];
1496 return CRM_Core_DAO
::$_nullObject;
1500 return self
::$worldRegions;
1504 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1506 * Get all Activity Statuses.
1508 * The static array activityStatus is returned
1511 * @param string $column
1514 * array reference of all activity statuses
1516 public static function &activityStatus($column = 'label') {
1517 if (NULL === self
::$activityStatus) {
1518 self
::$activityStatus = array();
1520 if (!array_key_exists($column, self
::$activityStatus)) {
1521 self
::$activityStatus[$column] = array();
1523 self
::$activityStatus[$column] = CRM_Core_OptionGroup
::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1526 return self
::$activityStatus[$column];
1530 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1532 * Get all Visibility levels.
1534 * The static array visibility is returned
1537 * @param string $column
1540 * array reference of all Visibility levels.
1542 public static function &visibility($column = 'label') {
1543 if (!isset(self
::$visibility)) {
1544 self
::$visibility = array();
1547 if (!isset(self
::$visibility[$column])) {
1548 self
::$visibility[$column] = CRM_Core_OptionGroup
::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1551 return self
::$visibility[$column];
1555 * @param int $countryID
1556 * @param string $field
1560 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1561 static $_cache = NULL;
1563 $cacheKey = "{$countryID}_{$field}";
1568 if (!empty($_cache[$cacheKey])) {
1569 return $_cache[$cacheKey];
1573 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1574 FROM civicrm_state_province
1575 WHERE country_id = %1
1584 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1587 while ($dao->fetch()) {
1588 $result[$dao->id
] = $dao->name
;
1591 // localise the stateProvince names if in an non-en_US locale
1592 $config = CRM_Core_Config
::singleton();
1594 if ($tsLocale != '' and $tsLocale != 'en_US') {
1595 $i18n = CRM_Core_I18n
::singleton();
1596 $i18n->localizeArray($result, array(
1597 'context' => 'province',
1599 $result = CRM_Utils_Array
::asort($result);
1602 $_cache[$cacheKey] = $result;
1604 CRM_Utils_Hook
::buildStateProvinceForCountry($countryID, $result);
1610 * @param int $stateID
1614 public static function &countyForState($stateID) {
1615 if (is_array($stateID)) {
1616 $states = implode(", ", $stateID);
1618 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1620 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1621 WHERE civicrm_county.state_province_id in ( $states )
1622 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1624 $dao = CRM_Core_DAO
::executeQuery($query);
1627 while ($dao->fetch()) {
1628 $result[$dao->id
] = $dao->abbreviation
. ': ' . $dao->name
;
1633 static $_cache = NULL;
1635 $cacheKey = "{$stateID}_name";
1640 if (!empty($_cache[$cacheKey])) {
1641 return $_cache[$cacheKey];
1645 SELECT civicrm_county.name name, civicrm_county.id id
1647 WHERE state_province_id = %1
1656 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1659 while ($dao->fetch()) {
1660 $result[$dao->id
] = $dao->name
;
1668 * Given a state ID return the country ID, this allows
1669 * us to populate forms and values for downstream code
1671 * @param int $stateID
1674 * the country id that the state belongs to
1676 public static function countryIDForStateID($stateID) {
1677 if (empty($stateID)) {
1678 return CRM_Core_DAO
::$_nullObject;
1683 FROM civicrm_state_province
1686 $params = array(1 => array($stateID, 'Integer'));
1688 return CRM_Core_DAO
::singleValueQuery($query, $params);
1692 * Get all types of Greetings.
1694 * The static array of greeting is returned
1698 * Get All Email Greetings - default is to get only active ones.
1700 * @param string $columnName
1703 * array reference of all greetings.
1705 public static function greeting($filter, $columnName = 'label') {
1706 $index = $filter['greeting_type'] . '_' . $columnName;
1708 // also add contactType to the array
1709 $contactType = CRM_Utils_Array
::value('contact_type', $filter);
1711 $index .= '_' . $contactType;
1714 if (NULL === self
::$greeting) {
1715 self
::$greeting = array();
1718 if (!CRM_Utils_Array
::value($index, self
::$greeting)) {
1719 $filterCondition = NULL;
1721 $filterVal = 'v.filter =';
1722 switch ($contactType) {
1731 case 'Organization':
1735 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1738 self
::$greeting[$index] = CRM_Core_OptionGroup
::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1741 return self
::$greeting[$index];
1745 * Construct array of default greeting values for contact type.
1749 * array reference of default greetings.
1751 public static function &greetingDefaults() {
1752 if (!self
::$greetingDefaults) {
1753 $defaultGreetings = array();
1754 $contactTypes = self
::get('CRM_Contact_DAO_Contact', 'contact_type', array(
1755 'keyColumn' => 'id',
1756 'labelColumn' => 'name',
1759 foreach ($contactTypes as $filter => $contactType) {
1760 $filterCondition = " AND (v.filter = 0 OR v.filter = $filter) AND v.is_default = 1 ";
1762 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1763 $tokenVal = CRM_Core_OptionGroup
::values($greeting, NULL, NULL, NULL, $filterCondition, 'label');
1764 $defaultGreetings[$contactType][$greeting] = $tokenVal;
1768 self
::$greetingDefaults = $defaultGreetings;
1771 return self
::$greetingDefaults;
1775 * Get all extensions.
1777 * The static array extensions
1779 * FIXME: This is called by civix but not by any core code. We
1780 * should provide an API call which civix can use instead.
1784 * array($fullyQualifiedName => $label) list of extensions
1786 public static function &getExtensions() {
1787 if (!self
::$extensions) {
1788 self
::$extensions = array();
1790 SELECT full_name, label
1791 FROM civicrm_extension
1794 $dao = CRM_Core_DAO
::executeQuery($sql);
1795 while ($dao->fetch()) {
1796 self
::$extensions[$dao->full_name
] = $dao->label
;
1800 return self
::$extensions;
1804 * Get all options values.
1806 * The static array option values is returned
1809 * @param bool $optionGroupName
1810 * Get All Option Group values- default is to get only active ones.
1813 * @param null $condition
1816 * array reference of all Option Group Name
1818 public static function accountOptionValues($optionGroupName, $id = NULL, $condition = NULL) {
1819 $cacheKey = $optionGroupName . '_' . $condition;
1820 if (empty(self
::$accountOptionValues[$cacheKey])) {
1821 self
::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup
::values($optionGroupName, FALSE, FALSE, FALSE, $condition);
1824 return CRM_Utils_Array
::value($id, self
::$accountOptionValues[$cacheKey]);
1827 return self
::$accountOptionValues[$cacheKey];
1831 * Fetch the list of active extensions of type 'module'
1833 * @param bool $fresh
1834 * Whether to forcibly reload extensions list from canonical store.
1837 * array(array('prefix' => $, 'file' => $))
1839 public static function getModuleExtensions($fresh = FALSE) {
1840 return CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles($fresh);
1845 * Get all tax rates.
1847 * The static array tax rates is returned
1850 * array list of tax rates with the financial type
1852 public static function getTaxRates() {
1853 if (!self
::$taxRates) {
1854 self
::$taxRates = array();
1856 SELECT fa.tax_rate, efa.entity_id
1857 FROM civicrm_entity_financial_account efa
1858 INNER JOIN civicrm_financial_account fa ON fa.id = efa.financial_account_id
1859 INNER JOIN civicrm_option_value cov ON cov.value = efa.account_relationship
1860 INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id
1861 WHERE efa.entity_table = 'civicrm_financial_type'
1862 AND cov.name = 'Sales Tax Account is'
1863 AND cog.name = 'account_relationship'
1864 AND fa.is_active = 1";
1865 $dao = CRM_Core_DAO
::executeQuery($sql);
1866 while ($dao->fetch()) {
1867 self
::$taxRates[$dao->entity_id
] = $dao->tax_rate
;
1871 return self
::$taxRates;