3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
50 class CRM_Core_PseudoConstant
{
53 * Static cache for pseudoconstant arrays
56 private static $cache;
59 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
64 private static $activityType;
70 private static $stateProvince;
76 private static $county;
79 * States/provinces abbreviations
82 private static $stateProvinceAbbreviation;
88 private static $country;
94 private static $countryIsoCode;
97 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
102 private static $group;
108 private static $groupIterator;
114 private static $relationshipType;
117 * Civicrm groups that are not smart groups
120 private static $staticGroup;
126 private static $currencyCode;
132 private static $paymentProcessor;
135 * Payment processor types
138 private static $paymentProcessorType;
144 private static $worldRegions;
147 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
152 private static $activityStatus;
158 private static $visibility;
164 private static $greeting;
170 private static $greetingDefaults;
173 * Extensions of type module
176 private static $extensions;
179 * Financial Account Type
182 private static $accountOptionValues;
188 private static $taxRates;
191 * Low-level option getter, rarely accessed directly.
192 * NOTE: Rather than calling this function directly use CRM_*_BAO_*::buildOptions()
193 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Pseudoconstant+%28option+list%29+Reference
195 * @param string $daoName
196 * @param string $fieldName
197 * @param array $params
198 * - name string name of the option group
199 * - flip boolean results are return in id => label format if false
200 * if true, the results are reversed
201 * - grouping boolean if true, return the value in 'grouping' column (currently unsupported for tables other than option_value)
202 * - localize boolean if true, localize the results before returning
203 * - condition string|array add condition(s) to the sql query - will be concatenated using 'AND'
204 * - keyColumn string the column to use for 'id'
205 * - labelColumn string the column to use for 'label'
206 * - orderColumn string the column to use for sorting, defaults to 'weight' column if one exists, else defaults to labelColumn
207 * - onlyActive boolean return only the action option values
208 * - fresh boolean ignore cache entries and go back to DB
209 * @param string $context : Context string
212 * array on success, FALSE on error.
215 public static function get($daoName, $fieldName, $params = array(), $context = NULL) {
216 CRM_Core_DAO
::buildOptionsContext($context);
217 $flip = !empty($params['flip']);
218 // Merge params with defaults
222 'onlyActive' => ($context == 'validate' ||
$context == 'get') ?
FALSE : TRUE,
226 // Custom fields are not in the schema
227 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
228 $customField = new CRM_Core_DAO_CustomField();
229 $customField->id
= (int) substr($fieldName, 7);
230 $customField->find(TRUE);
233 if (!empty($customField->option_group_id
)) {
234 $options = CRM_Core_OptionGroup
::valuesByID($customField->option_group_id
,
238 // Note: for custom fields the 'name' column is NULL
239 CRM_Utils_Array
::value('labelColumn', $params, 'label'),
240 $params['onlyActive'],
245 if ($customField->data_type
=== 'StateProvince') {
246 $options = self
::stateProvince();
248 elseif ($customField->data_type
=== 'Country') {
249 $options = $context == 'validate' ? self
::countryIsoCode() : self
::country();
251 elseif ($customField->data_type
=== 'Boolean') {
252 $options = $context == 'validate' ?
array(0, 1) : array(1 => ts('Yes'), 0 => ts('No'));
255 CRM_Utils_Hook
::customFieldOptions($customField->id
, $options, FALSE);
256 if ($options && $flip) {
257 $options = array_flip($options);
259 $customField->free();
263 // Core field: load schema
264 $dao = new $daoName();
265 $fieldSpec = $dao->getFieldSpec($fieldName);
267 // If neither worked then this field doesn't exist. Return false.
268 if (empty($fieldSpec)) {
272 elseif (!empty($fieldSpec['pseudoconstant'])) {
273 $pseudoconstant = $fieldSpec['pseudoconstant'];
275 // if callback is specified..
276 if (!empty($pseudoconstant['callback'])) {
277 list($className, $fnName) = explode('::', $pseudoconstant['callback']);
278 if (method_exists($className, $fnName)) {
279 return call_user_func(array($className, $fnName));
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 // Fetch option group from option_value table
291 if (!empty($pseudoconstant['optionGroupName'])) {
292 if ($context == 'validate') {
293 $params['labelColumn'] = 'name';
295 // Call our generic fn for retrieving from the option_value table
296 return CRM_Core_OptionGroup
::values(
297 $pseudoconstant['optionGroupName'],
301 $params['condition'] ?
' AND ' . implode(' AND ', (array) $params['condition']) : NULL,
302 $params['labelColumn'] ?
$params['labelColumn'] : 'label',
303 $params['onlyActive'],
305 $params['keyColumn'] ?
$params['keyColumn'] : 'value'
309 // Fetch options from other tables
310 if (!empty($pseudoconstant['table'])) {
311 // Normalize params so the serialized cache string will be consistent.
312 CRM_Utils_Array
::remove($params, 'flip', 'fresh');
314 $cacheKey = $daoName . $fieldName . serialize($params);
316 // Retrieve cached options
317 if (isset(self
::$cache[$cacheKey]) && empty($params['fresh'])) {
318 $output = self
::$cache[$cacheKey];
321 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($pseudoconstant['table']);
322 if (!class_exists($daoName)) {
325 // Get list of fields for the option table
326 $dao = new $daoName();
327 $availableFields = array_keys($dao->fieldKeys());
330 $select = "SELECT %1 AS id, %2 AS label";
333 $order = "ORDER BY %2";
335 // Use machine name instead of label in validate context
336 if ($context == 'validate') {
337 if (!empty($pseudoconstant['nameColumn'])) {
338 $params['labelColumn'] = $pseudoconstant['nameColumn'];
340 elseif (in_array('name', $availableFields)) {
341 $params['labelColumn'] = 'name';
344 // Condition param can be passed as an sql clause string or an array of clauses
345 if (!empty($params['condition'])) {
346 $wheres[] = implode(' AND ', (array) $params['condition']);
348 // onlyActive param will automatically filter on common flags
349 if (!empty($params['onlyActive'])) {
350 foreach (array('is_active' => 1, 'is_deleted' => 0, 'is_test' => 0) as $flag => $val) {
351 if (in_array($flag, $availableFields)) {
352 $wheres[] = "$flag = $val";
356 // Filter domain specific options
357 if (in_array('domain_id', $availableFields)) {
358 $wheres[] = 'domain_id = ' . CRM_Core_Config
::domainID();
360 $queryParams = array(
361 1 => array($params['keyColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
362 2 => array($params['labelColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
363 3 => array($pseudoconstant['table'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
365 // Add orderColumn param
366 if (!empty($params['orderColumn'])) {
367 $queryParams[4] = array($params['orderColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
);
368 $order = "ORDER BY %4";
370 // Support no sorting if $params[orderColumn] is FALSE
371 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
374 // Default to 'weight' if that column exists
375 elseif (in_array('weight', $availableFields)) {
376 $order = "ORDER BY weight";
380 $query = "$select $from";
382 $query .= " WHERE " . implode($wheres, ' AND ');
384 $query .= ' ' . $order;
385 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
386 while ($dao->fetch()) {
387 $output[$dao->id
] = $dao->label
;
391 if (!empty($params['localize']) ||
$pseudoconstant['table'] == 'civicrm_country' ||
$pseudoconstant['table'] == 'civicrm_state_province') {
392 $I18nParams = array();
393 if ($pseudoconstant['table'] == 'civicrm_country') {
394 $I18nParams['context'] = 'country';
396 if ($pseudoconstant['table'] == 'civicrm_state_province') {
397 $I18nParams['context'] = 'province';
399 $i18n = CRM_Core_I18n
::singleton();
400 $i18n->localizeArray($output, $I18nParams);
401 // Maintain sort by label
402 if ($order == "ORDER BY %2") {
403 CRM_Utils_Array
::asort($output);
406 self
::$cache[$cacheKey] = $output;
408 return $flip ?
array_flip($output) : $output;
412 // Return "Yes" and "No" for boolean fields
413 elseif (CRM_Utils_Array
::value('type', $fieldSpec) === CRM_Utils_Type
::T_BOOLEAN
) {
414 $output = $context == 'validate' ?
array(0, 1) : array(1 => ts('Yes'), 0 => ts('No'));
415 return $flip ?
array_flip($output) : $output;
417 // If we're still here, it's an error. Return FALSE.
422 * Fetch the translated label for a field given its key
424 * @param string $baoName
425 * @param string $fieldName
426 * @param string|Int $key
428 * TODO: Accept multivalued input?
430 * @return bool|null|string
431 * FALSE if the given field has no associated option list
432 * NULL if the given key has no corresponding option
433 * String if label is found
435 public static function getLabel($baoName, $fieldName, $key) {
436 $values = $baoName::buildOptions($fieldName, 'get');
437 if ($values === FALSE) {
440 return CRM_Utils_Array
::value($key, $values);
444 * Fetch the machine name for a field given its key
446 * @param string $baoName
447 * @param string $fieldName
448 * @param string|Int $key
450 * @return bool|null|string
451 * FALSE if the given field has no associated option list
452 * NULL if the given key has no corresponding option
453 * String if label is found
455 public static function getName($baoName, $fieldName, $key) {
456 $values = $baoName::buildOptions($fieldName, 'validate');
457 if ($values === FALSE) {
460 return CRM_Utils_Array
::value($key, $values);
464 * Fetch the key for a field option given its name
466 * @param string $baoName
467 * @param string $fieldName
468 * @param string|Int $value
470 * @return bool|null|string|int
471 * FALSE if the given field has no associated option list
472 * NULL if the given key has no corresponding option
473 * String|Number if key is found
475 public static function getKey($baoName, $fieldName, $value) {
476 $values = $baoName::buildOptions($fieldName, 'validate');
477 if ($values === FALSE) {
480 return CRM_Utils_Array
::key($value, $values);
484 * Lookup the admin page at which a field's option list can be edited
486 * @return string|null
488 public static function getOptionEditUrl($fieldSpec) {
489 // If it's an option group, that's easy
490 if (!empty($fieldSpec['pseudoconstant']['optionGroupName'])) {
491 return 'civicrm/admin/options/' . $fieldSpec['pseudoconstant']['optionGroupName'];
493 // For everything else...
494 elseif (!empty($fieldSpec['pseudoconstant']['table'])) {
495 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($fieldSpec['pseudoconstant']['table']);
499 // We don't have good mapping so have to do a bit of guesswork from the menu
500 list(, $parent, , $child) = explode('_', $daoName);
501 $sql = "SELECT path FROM civicrm_menu
502 WHERE page_callback LIKE '%CRM_Admin_Page_$child%' OR page_callback LIKE '%CRM_{$parent}_Page_$child%'
503 ORDER BY page_callback
505 return CRM_Core_Dao
::singleValueQuery($sql);
511 * DEPRECATED generic populate method
512 * All pseudoconstant functions that use this method are also @deprecated
514 * The static array $var is populated from the db
515 * using the <b>$name DAO</b>.
517 * Note: any database errors will be trapped by the DAO.
520 * The associative array we will fill.
521 * @param string $name
522 * The name of the DAO.
524 * Get all objects. default is to get only active ones.
525 * @param string $retrieve
526 * The field that we are interested in (normally name, differs in some objects).
527 * @param string $filter
528 * The field that we want to filter the result set with.
529 * @param string $condition
530 * The condition that gets passed to the final query as the WHERE clause.
532 * @param null $orderby
538 public static function populate(
543 $filter = 'is_active',
549 $cacheKey = "CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}";
550 $cache = CRM_Utils_Cache
::singleton();
551 $var = $cache->get($cacheKey);
552 if ($var && empty($force)) {
556 $object = new $name();
558 $object->selectAdd();
559 $object->selectAdd("$key, $retrieve");
561 $object->whereAdd($condition);
565 $object->orderBy($retrieve);
568 $object->orderBy($orderby);
572 $object->$filter = 1;
577 while ($object->fetch()) {
578 $var[$object->$key] = $object->$retrieve;
581 $cache->set($cacheKey, $var);
585 * Flush given pseudoconstant so it can be reread from db
586 * nex time it's requested.
589 * @param bool|string $name pseudoconstant to be flushed
591 public static function flush($name = 'cache') {
592 if (isset(self
::$
$name)) {
595 if ($name == 'cache') {
596 CRM_Core_OptionGroup
::flushAll();
601 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
603 * Get all Activty types.
605 * The static array activityType is returned
609 * array reference of all activity types.
611 public static function &activityType() {
612 $args = func_get_args();
613 $all = CRM_Utils_Array
::value(0, $args, TRUE);
614 $includeCaseActivities = CRM_Utils_Array
::value(1, $args, FALSE);
615 $reset = CRM_Utils_Array
::value(2, $args, FALSE);
616 $returnColumn = CRM_Utils_Array
::value(3, $args, 'label');
617 $includeCampaignActivities = CRM_Utils_Array
::value(4, $args, FALSE);
618 $onlyComponentActivities = CRM_Utils_Array
::value(5, $args, FALSE);
619 $index = (int) $all . '_' . $returnColumn . '_' . (int) $includeCaseActivities;
620 $index .= '_' . (int) $includeCampaignActivities;
621 $index .= '_' . (int) $onlyComponentActivities;
623 if (NULL === self
::$activityType) {
624 self
::$activityType = array();
627 if (!isset(self
::$activityType[$index]) ||
$reset) {
630 $condition = 'AND filter = 0';
632 $componentClause = " v.component_id IS NULL";
633 if ($onlyComponentActivities) {
634 $componentClause = " v.component_id IS NOT NULL";
637 $componentIds = array();
638 $compInfo = CRM_Core_Component
::getEnabledComponents();
640 // build filter for listing activity types only if their
641 // respective components are enabled
642 foreach ($compInfo as $compName => $compObj) {
643 if ($compName == 'CiviCase') {
644 if ($includeCaseActivities) {
645 $componentIds[] = $compObj->componentID
;
648 elseif ($compName == 'CiviCampaign') {
649 if ($includeCampaignActivities) {
650 $componentIds[] = $compObj->componentID
;
654 $componentIds[] = $compObj->componentID
;
658 if (count($componentIds)) {
659 $componentIds = implode(',', $componentIds);
660 $componentClause = " ($componentClause OR v.component_id IN ($componentIds))";
661 if ($onlyComponentActivities) {
662 $componentClause = " ( v.component_id IN ($componentIds ) )";
665 $condition = $condition . ' AND ' . $componentClause;
667 self
::$activityType[$index] = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
669 return self
::$activityType[$index];
673 * Get all the State/Province from database.
675 * The static array stateProvince is returned, and if it's
676 * called the first time, the <b>State Province DAO</b> is used
677 * to get all the States.
679 * Note: any database errors will be trapped by the DAO.
682 * @param bool|int $id - Optional id to return
687 * array reference of all State/Provinces.
689 public static function &stateProvince($id = FALSE, $limit = TRUE) {
690 if (($id && !CRM_Utils_Array
::value($id, self
::$stateProvince)) ||
!self
::$stateProvince ||
!$id) {
691 $whereClause = FALSE;
692 $config = CRM_Core_Config
::singleton();
694 $countryIsoCodes = self
::countryIsoCode();
695 $limitCodes = $config->provinceLimit();
697 foreach ($limitCodes as $code) {
698 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
700 if (!empty($limitIds)) {
701 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
704 $whereClause = FALSE;
707 self
::populate(self
::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
709 // localise the province names if in an non-en_US locale
711 if ($tsLocale != '' and $tsLocale != 'en_US') {
712 $i18n = CRM_Core_I18n
::singleton();
713 $i18n->localizeArray(self
::$stateProvince, array(
714 'context' => 'province',
716 self
::$stateProvince = CRM_Utils_Array
::asort(self
::$stateProvince);
720 if (array_key_exists($id, self
::$stateProvince)) {
721 return self
::$stateProvince[$id];
728 return self
::$stateProvince;
732 * Get all the State/Province abbreviations from the database.
734 * Same as above, except gets the abbreviations instead of the names.
737 * @param bool|int $id - Optional id to return
742 * array reference of all State/Province abbreviations.
744 public static function &stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
748 FROM civicrm_state_province
756 return CRM_Core_DAO
::singleValueQuery($query, $params);
759 if (!self
::$stateProvinceAbbreviation ||
!$id) {
761 $whereClause = FALSE;
764 $config = CRM_Core_Config
::singleton();
765 $countryIsoCodes = self
::countryIsoCode();
766 $limitCodes = $config->provinceLimit();
768 foreach ($limitCodes as $code) {
769 $tmpArray = array_keys($countryIsoCodes, $code);
771 if (!empty($tmpArray)) {
772 $limitIds[] = array_shift($tmpArray);
775 if (!empty($limitIds)) {
776 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
779 self
::populate(self
::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
783 if (array_key_exists($id, self
::$stateProvinceAbbreviation)) {
784 return self
::$stateProvinceAbbreviation[$id];
791 return self
::$stateProvinceAbbreviation;
795 * Get all the countries from database.
797 * The static array country is returned, and if it's
798 * called the first time, the <b>Country DAO</b> is used
799 * to get all the countries.
801 * Note: any database errors will be trapped by the DAO.
804 * @param bool|int $id - Optional id to return
806 * @param bool $applyLimit
809 * array reference of all countries.
811 public static function country($id = FALSE, $applyLimit = TRUE) {
812 if (($id && !CRM_Utils_Array
::value($id, self
::$country)) ||
!self
::$country ||
!$id) {
814 $config = CRM_Core_Config
::singleton();
815 $limitCodes = array();
818 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
819 // (ensuring it's a subset of the legal values)
820 // K/P: We need to fix this, i dont think it works with new setting files
821 $limitCodes = $config->countryLimit();
822 if (!is_array($limitCodes)) {
824 $config->countryLimit
=> 1,
828 $limitCodes = array_intersect(self
::countryIsoCode(), $limitCodes);
831 if (count($limitCodes)) {
832 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
838 self
::populate(self
::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
840 // if default country is set, percolate it to the top
841 if ($config->defaultContactCountry()) {
842 $countryIsoCodes = self
::countryIsoCode();
843 $defaultID = array_search($config->defaultContactCountry(), $countryIsoCodes);
844 if ($defaultID !== FALSE) {
845 $default[$defaultID] = CRM_Utils_Array
::value($defaultID, self
::$country);
846 self
::$country = $default + self
::$country;
850 // localise the country names if in an non-en_US locale
852 if ($tsLocale != '' and $tsLocale != 'en_US') {
853 $i18n = CRM_Core_I18n
::singleton();
854 $i18n->localizeArray(self
::$country, array(
855 'context' => 'country',
857 self
::$country = CRM_Utils_Array
::asort(self
::$country);
861 if (array_key_exists($id, self
::$country)) {
862 return self
::$country[$id];
865 return CRM_Core_DAO
::$_nullObject;
868 return self
::$country;
872 * Get all the country ISO Code abbreviations from the database.
874 * The static array countryIsoCode is returned, and if it's
875 * called the first time, the <b>Country DAO</b> is used
876 * to get all the countries' ISO codes.
878 * Note: any database errors will be trapped by the DAO.
884 * array reference of all country ISO codes.
886 public static function &countryIsoCode($id = FALSE) {
887 if (!self
::$countryIsoCode) {
888 self
::populate(self
::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
891 if (array_key_exists($id, self
::$countryIsoCode)) {
892 return self
::$countryIsoCode[$id];
895 return CRM_Core_DAO
::$_nullObject;
898 return self
::$countryIsoCode;
902 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
904 * Get all groups from database
906 * The static array group is returned, and if it's
907 * called the first time, the <b>Group DAO</b> is used
908 * to get all the groups.
910 * Note: any database errors will be trapped by the DAO.
912 * @param string $groupType
913 * Type of group(Access/Mailing).
914 * @param bool $excludeHidden
915 * Exclude hidden groups.
919 * array reference of all groups.
921 public static function &allGroup($groupType = NULL, $excludeHidden = TRUE) {
922 $condition = CRM_Contact_BAO_Group
::groupTypeCondition($groupType, $excludeHidden);
925 self
::$group = array();
928 $groupKey = $groupType ?
$groupType : 'null';
930 if (!isset(self
::$group[$groupKey])) {
931 self
::$group[$groupKey] = NULL;
932 self
::populate(self
::$group[$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
934 return self
::$group[$groupKey];
938 * Create or get groups iterator (iterates over nested groups in a
941 * The GroupNesting instance is returned; it's created if this is being
942 * called for the first time
946 * @param bool $styledLabels
948 * @return CRM_Contact_BAO_GroupNesting
950 public static function &groupIterator($styledLabels = FALSE) {
951 if (!self
::$groupIterator) {
952 // When used as an object, GroupNesting implements Iterator
953 // and iterates nested groups in a logical manner for us
954 self
::$groupIterator = new CRM_Contact_BAO_GroupNesting($styledLabels);
956 return self
::$groupIterator;
960 * Get all permissioned groups from database
962 * The static array group is returned, and if it's
963 * called the first time, the <b>Group DAO</b> is used
964 * to get all the groups.
966 * Note: any database errors will be trapped by the DAO.
968 * @param string $groupType
969 * Type of group(Access/Mailing).
970 * @param bool $excludeHidden
971 * Exclude hidden groups.
975 * array reference of all groups.
977 public static function group($groupType = NULL, $excludeHidden = TRUE) {
978 return CRM_Core_Permission
::group($groupType, $excludeHidden);
982 * Fetch groups in a nested format suitable for use in select form element
983 * @param bool $checkPermissions
984 * @param string|null $groupType
985 * @param bool $excludeHidden
988 public static function nestedGroup($checkPermissions = TRUE, $groupType = NULL, $excludeHidden = TRUE) {
989 $groups = $checkPermissions ? self
::group($groupType, $excludeHidden) : self
::allGroup($groupType, $excludeHidden);
990 return CRM_Contact_BAO_Group
::getGroupsHierarchy($groups, NULL, ' ', TRUE);
994 * Get all permissioned groups from database
996 * The static array group is returned, and if it's
997 * called the first time, the <b>Group DAO</b> is used
998 * to get all the groups.
1000 * Note: any database errors will be trapped by the DAO.
1003 * @param bool $onlyPublic
1004 * @param null $groupType
1005 * @param bool $excludeHidden
1008 * array reference of all groups.
1010 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
1011 if (!self
::$staticGroup) {
1012 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
1014 $condition .= " AND visibility != 'User and User Admin Only'";
1018 $condition .= ' AND ' . CRM_Contact_BAO_Group
::groupTypeCondition($groupType);
1021 if ($excludeHidden) {
1022 $condition .= ' AND is_hidden != 1 ';
1025 self
::populate(self
::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
1028 return self
::$staticGroup;
1032 * Get all Relationship Types from database.
1034 * The static array group is returned, and if it's
1035 * called the first time, the <b>RelationshipType DAO</b> is used
1036 * to get all the relationship types.
1038 * Note: any database errors will be trapped by the DAO.
1040 * @param string $valueColumnName
1041 * Db column name/label.
1042 * @param bool $reset
1043 * Reset relationship types if true.
1047 * array reference of all relationship types.
1049 public static function &relationshipType($valueColumnName = 'label', $reset = FALSE) {
1050 if (!CRM_Utils_Array
::value($valueColumnName, self
::$relationshipType) ||
$reset) {
1051 self
::$relationshipType[$valueColumnName] = array();
1053 //now we have name/label columns CRM-3336
1054 $column_a_b = "{$valueColumnName}_a_b";
1055 $column_b_a = "{$valueColumnName}_b_a";
1057 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1058 $relationshipTypeDAO->selectAdd();
1059 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1060 $relationshipTypeDAO->is_active
= 1;
1061 $relationshipTypeDAO->find();
1062 while ($relationshipTypeDAO->fetch()) {
1064 self
::$relationshipType[$valueColumnName][$relationshipTypeDAO->id
] = array(
1065 'id' => $relationshipTypeDAO->id
,
1066 $column_a_b => $relationshipTypeDAO->$column_a_b,
1067 $column_b_a => $relationshipTypeDAO->$column_b_a,
1068 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1069 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1070 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1071 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1076 return self
::$relationshipType[$valueColumnName];
1080 * Get all the ISO 4217 currency codes
1082 * so far, we use this for validation only, so there's no point of putting this into the database
1086 * array reference of all currency codes
1088 public static function ¤cyCode() {
1089 if (!self
::$currencyCode) {
1090 self
::$currencyCode = array(
1360 return self
::$currencyCode;
1364 * Get all the County from database.
1366 * The static array county is returned, and if it's
1367 * called the first time, the <b>County DAO</b> is used
1368 * to get all the Counties.
1370 * Note: any database errors will be trapped by the DAO.
1373 * @param bool|int $id - Optional id to return
1376 * array reference of all Counties
1378 public static function &county($id = FALSE) {
1379 if (!self
::$county) {
1381 $config = CRM_Core_Config
::singleton();
1382 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1383 self
::populate(self
::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1386 if (array_key_exists($id, self
::$county)) {
1387 return self
::$county[$id];
1390 return CRM_Core_DAO
::$_nullObject;
1393 return self
::$county;
1397 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1398 * Get all active payment processors
1400 * The static array paymentProcessor is returned
1404 * Get payment processors - default is to get only active ones.
1406 * Get test payment processors.
1408 * @param null $additionalCond
1411 * array of all payment processors
1413 public static function &paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1414 $condition = "is_test = ";
1415 $condition .= ($test) ?
'1' : '0';
1417 if ($additionalCond) {
1418 $condition .= " AND ( $additionalCond ) ";
1421 // CRM-7178. Make sure we only include payment processors valid in ths
1423 $condition .= " AND domain_id = " . CRM_Core_Config
::domainID();
1425 $cacheKey = $condition . '_' . (int) $all;
1426 if (!isset(self
::$paymentProcessor[$cacheKey])) {
1427 self
::populate(self
::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1430 return self
::$paymentProcessor[$cacheKey];
1434 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1436 * The static array paymentProcessorType is returned
1440 * Get payment processors - default is to get only active ones.
1443 * @param string $return
1446 * array of all payment processor types
1448 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1449 $cacheKey = $id . '_' . $return;
1450 if (empty(self
::$paymentProcessorType[$cacheKey])) {
1451 self
::populate(self
::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1453 if ($id && CRM_Utils_Array
::value($id, self
::$paymentProcessorType[$cacheKey])) {
1454 return self
::$paymentProcessorType[$cacheKey][$id];
1456 return self
::$paymentProcessorType[$cacheKey];
1460 * Get all the World Regions from Database
1466 * array reference of all World Regions
1468 public static function &worldRegion($id = FALSE) {
1469 if (!self
::$worldRegions) {
1470 self
::populate(self
::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1474 if (array_key_exists($id, self
::$worldRegions)) {
1475 return self
::$worldRegions[$id];
1478 return CRM_Core_DAO
::$_nullObject;
1482 return self
::$worldRegions;
1486 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1488 * Get all Activity Statuses.
1490 * The static array activityStatus is returned
1493 * @param string $column
1496 * array reference of all activity statuses
1498 public static function &activityStatus($column = 'label') {
1499 if (NULL === self
::$activityStatus) {
1500 self
::$activityStatus = array();
1502 if (!array_key_exists($column, self
::$activityStatus)) {
1503 self
::$activityStatus[$column] = array();
1505 self
::$activityStatus[$column] = CRM_Core_OptionGroup
::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1508 return self
::$activityStatus[$column];
1512 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1514 * Get all Visibility levels.
1516 * The static array visibility is returned
1519 * @param string $column
1522 * array reference of all Visibility levels.
1524 public static function &visibility($column = 'label') {
1525 if (!isset(self
::$visibility)) {
1526 self
::$visibility = array();
1529 if (!isset(self
::$visibility[$column])) {
1530 self
::$visibility[$column] = CRM_Core_OptionGroup
::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1533 return self
::$visibility[$column];
1537 * @param int $countryID
1538 * @param string $field
1542 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1543 static $_cache = NULL;
1545 $cacheKey = "{$countryID}_{$field}";
1550 if (!empty($_cache[$cacheKey])) {
1551 return $_cache[$cacheKey];
1555 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1556 FROM civicrm_state_province
1557 WHERE country_id = %1
1566 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1569 while ($dao->fetch()) {
1570 $result[$dao->id
] = $dao->name
;
1573 // localise the stateProvince names if in an non-en_US locale
1574 $config = CRM_Core_Config
::singleton();
1576 if ($tsLocale != '' and $tsLocale != 'en_US') {
1577 $i18n = CRM_Core_I18n
::singleton();
1578 $i18n->localizeArray($result, array(
1579 'context' => 'province',
1581 $result = CRM_Utils_Array
::asort($result);
1584 $_cache[$cacheKey] = $result;
1586 CRM_Utils_Hook
::buildStateProvinceForCountry($countryID, $result);
1592 * @param int $stateID
1596 public static function &countyForState($stateID) {
1597 if (is_array($stateID)) {
1598 $states = implode(", ", $stateID);
1600 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1602 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1603 WHERE civicrm_county.state_province_id in ( $states )
1604 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1606 $dao = CRM_Core_DAO
::executeQuery($query);
1609 while ($dao->fetch()) {
1610 $result[$dao->id
] = $dao->abbreviation
. ': ' . $dao->name
;
1615 static $_cache = NULL;
1617 $cacheKey = "{$stateID}_name";
1622 if (!empty($_cache[$cacheKey])) {
1623 return $_cache[$cacheKey];
1627 SELECT civicrm_county.name name, civicrm_county.id id
1629 WHERE state_province_id = %1
1638 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1641 while ($dao->fetch()) {
1642 $result[$dao->id
] = $dao->name
;
1650 * Given a state ID return the country ID, this allows
1651 * us to populate forms and values for downstream code
1653 * @param int $stateID
1656 * the country id that the state belongs to
1658 public static function countryIDForStateID($stateID) {
1659 if (empty($stateID)) {
1660 return CRM_Core_DAO
::$_nullObject;
1665 FROM civicrm_state_province
1668 $params = array(1 => array($stateID, 'Integer'));
1670 return CRM_Core_DAO
::singleValueQuery($query, $params);
1674 * Get all types of Greetings.
1676 * The static array of greeting is returned
1680 * Get All Email Greetings - default is to get only active ones.
1682 * @param string $columnName
1685 * array reference of all greetings.
1687 public static function greeting($filter, $columnName = 'label') {
1688 $index = $filter['greeting_type'] . '_' . $columnName;
1690 // also add contactType to the array
1691 $contactType = CRM_Utils_Array
::value('contact_type', $filter);
1693 $index .= '_' . $contactType;
1696 if (NULL === self
::$greeting) {
1697 self
::$greeting = array();
1700 if (!CRM_Utils_Array
::value($index, self
::$greeting)) {
1701 $filterCondition = NULL;
1703 $filterVal = 'v.filter =';
1704 switch ($contactType) {
1713 case 'Organization':
1717 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1720 self
::$greeting[$index] = CRM_Core_OptionGroup
::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1723 return self
::$greeting[$index];
1727 * Construct array of default greeting values for contact type
1731 * array reference of default greetings.
1733 public static function &greetingDefaults() {
1734 if (!self
::$greetingDefaults) {
1735 $defaultGreetings = array();
1736 $contactTypes = self
::get('CRM_Contact_DAO_Contact', 'contact_type', array(
1737 'keyColumn' => 'id',
1738 'labelColumn' => 'name',
1741 foreach ($contactTypes as $filter => $contactType) {
1742 $filterCondition = " AND (v.filter = 0 OR v.filter = $filter) AND v.is_default = 1 ";
1744 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1745 $tokenVal = CRM_Core_OptionGroup
::values($greeting, NULL, NULL, NULL, $filterCondition, 'label');
1746 $defaultGreetings[$contactType][$greeting] = $tokenVal;
1750 self
::$greetingDefaults = $defaultGreetings;
1753 return self
::$greetingDefaults;
1757 * Get all extensions
1759 * The static array extensions
1761 * FIXME: This is called by civix but not by any core code. We
1762 * should provide an API call which civix can use instead.
1766 * array($fullyQualifiedName => $label) list of extensions
1768 public static function &getExtensions() {
1769 if (!self
::$extensions) {
1770 self
::$extensions = array();
1772 SELECT full_name, label
1773 FROM civicrm_extension
1776 $dao = CRM_Core_DAO
::executeQuery($sql);
1777 while ($dao->fetch()) {
1778 self
::$extensions[$dao->full_name
] = $dao->label
;
1782 return self
::$extensions;
1786 * Get all options values
1788 * The static array option values is returned
1791 * @param bool $optionGroupName
1792 * Get All Option Group values- default is to get only active ones.
1795 * @param null $condition
1798 * array reference of all Option Group Name
1800 public static function accountOptionValues($optionGroupName, $id = NULL, $condition = NULL) {
1801 $cacheKey = $optionGroupName . '_' . $condition;
1802 if (empty(self
::$accountOptionValues[$cacheKey])) {
1803 self
::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup
::values($optionGroupName, FALSE, FALSE, FALSE, $condition);
1806 return CRM_Utils_Array
::value($id, self
::$accountOptionValues[$cacheKey]);
1809 return self
::$accountOptionValues[$cacheKey];
1813 * Fetch the list of active extensions of type 'module'
1815 * @param bool $fresh
1816 * Whether to forcibly reload extensions list from canonical store.
1819 * array(array('prefix' => $, 'file' => $))
1821 public static function getModuleExtensions($fresh = FALSE) {
1822 return CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles($fresh);
1829 * The static array tax rates is returned
1832 * array list of tax rates with the financial type
1834 public static function getTaxRates() {
1835 if (!self
::$taxRates) {
1836 self
::$taxRates = array();
1838 SELECT fa.tax_rate, efa.entity_id
1839 FROM civicrm_entity_financial_account efa
1840 INNER JOIN civicrm_financial_account fa ON fa.id = efa.financial_account_id
1841 INNER JOIN civicrm_option_value cov ON cov.value = efa.account_relationship
1842 INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id
1843 WHERE efa.entity_table = 'civicrm_financial_type'
1844 AND cov.name = 'Sales Tax Account is'
1845 AND cog.name = 'account_relationship'
1846 AND fa.is_active = 1";
1847 $dao = CRM_Core_DAO
::executeQuery($sql);
1848 while ($dao->fetch()) {
1849 self
::$taxRates[$dao->entity_id
] = $dao->tax_rate
;
1853 return self
::$taxRates;