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
57 private static $cache;
60 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
66 private static $activityType;
73 private static $stateProvince;
80 private static $county;
83 * States/provinces abbreviations
87 private static $stateProvinceAbbreviation;
94 private static $country;
101 private static $countryIsoCode;
104 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
110 private static $group;
117 private static $groupIterator;
124 private static $relationshipType;
127 * Civicrm groups that are not smart groups
131 private static $staticGroup;
138 private static $currencyCode;
145 private static $paymentProcessor;
148 * Payment processor types
152 private static $paymentProcessorType;
159 private static $worldRegions;
162 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
168 private static $activityStatus;
175 private static $visibility;
182 private static $greeting;
189 private static $greetingDefaults;
192 * Extensions of type module
196 private static $extensions;
199 * Financial Account Type
203 private static $accountOptionValues;
210 private static $taxRates;
213 * Low-level option getter, rarely accessed directly.
214 * NOTE: Rather than calling this function directly use CRM_*_BAO_*::buildOptions()
215 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Pseudoconstant+%28option+list%29+Reference
217 * @param string $daoName
218 * @param string $fieldName
219 * @param array $params
220 * - name string name of the option group
221 * - flip boolean results are return in id => label format if false
222 * if true, the results are reversed
223 * - grouping boolean if true, return the value in 'grouping' column (currently unsupported for tables other than option_value)
224 * - localize boolean if true, localize the results before returning
225 * - condition string|array add condition(s) to the sql query - will be concatenated using 'AND'
226 * - keyColumn string the column to use for 'id'
227 * - labelColumn string the column to use for 'label'
228 * - orderColumn string the column to use for sorting, defaults to 'weight' column if one exists, else defaults to labelColumn
229 * - onlyActive boolean return only the action option values
230 * - fresh boolean ignore cache entries and go back to DB
231 * @param string $context: Context string
233 * @return Array|bool - array on success, FALSE on error.
237 public static function get($daoName, $fieldName, $params = array(), $context = NULL) {
238 CRM_Core_DAO
::buildOptionsContext($context);
239 $flip = !empty($params['flip']);
240 // Merge params with defaults
244 'onlyActive' => ($context == 'validate' ||
$context == 'get') ?
FALSE : TRUE,
248 // Custom fields are not in the schema
249 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
250 $customField = new CRM_Core_DAO_CustomField();
251 $customField->id
= (int) substr($fieldName, 7);
252 $customField->find(TRUE);
255 if (!empty($customField->option_group_id
)) {
256 $options = CRM_Core_OptionGroup
::valuesByID($customField->option_group_id
,
260 // Note: for custom fields the 'name' column is NULL
261 CRM_Utils_Array
::value('labelColumn', $params, 'label'),
262 $params['onlyActive'],
267 if ($customField->data_type
=== 'StateProvince') {
268 $options = self
::stateProvince();
270 elseif ($customField->data_type
=== 'Country') {
271 $options = $context == 'validate' ? self
::countryIsoCode() : self
::country();
273 elseif ($customField->data_type
=== 'Boolean') {
274 $options = $context == 'validate' ?
array(0, 1) : array(1 => ts('Yes'), 0 => ts('No'));
277 CRM_Utils_Hook
::customFieldOptions($customField->id
, $options, FALSE);
278 if ($options && $flip) {
279 $options = array_flip($options);
281 $customField->free();
285 // Core field: load schema
287 $fieldSpec = $dao->getFieldSpec($fieldName);
289 // If neither worked then this field doesn't exist. Return false.
290 if (empty($fieldSpec)) {
294 elseif (!empty($fieldSpec['pseudoconstant'])) {
295 $pseudoconstant = $fieldSpec['pseudoconstant'];
297 // if callback is specified..
298 if (!empty($pseudoconstant['callback'])) {
299 list($className, $fnName) = explode('::', $pseudoconstant['callback']);
300 if (method_exists($className, $fnName)) {
301 return call_user_func(array($className, $fnName));
305 // Merge params with schema defaults
307 'condition' => CRM_Utils_Array
::value('condition', $pseudoconstant, array()),
308 'keyColumn' => CRM_Utils_Array
::value('keyColumn', $pseudoconstant),
309 'labelColumn' => CRM_Utils_Array
::value('labelColumn', $pseudoconstant),
312 // Fetch option group from option_value table
313 if (!empty($pseudoconstant['optionGroupName'])) {
314 if ($context == 'validate') {
315 $params['labelColumn'] = 'name';
317 // Call our generic fn for retrieving from the option_value table
318 return CRM_Core_OptionGroup
::values(
319 $pseudoconstant['optionGroupName'],
323 $params['condition'] ?
' AND ' . implode(' AND ', (array) $params['condition']) : NULL,
324 $params['labelColumn'] ?
$params['labelColumn'] : 'label',
325 $params['onlyActive'],
327 $params['keyColumn'] ?
$params['keyColumn'] : 'value'
331 // Fetch options from other tables
332 if (!empty($pseudoconstant['table'])) {
333 // Normalize params so the serialized cache string will be consistent.
334 CRM_Utils_Array
::remove($params, 'flip', 'fresh');
336 $cacheKey = $daoName . $fieldName . serialize($params);
338 // Retrieve cached options
339 if (isset(self
::$cache[$cacheKey]) && empty($params['fresh'])) {
340 $output = self
::$cache[$cacheKey];
343 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($pseudoconstant['table']);
344 if (!class_exists($daoName)) {
347 // Get list of fields for the option table
349 $availableFields = array_keys($dao->fieldKeys());
352 $select = "SELECT %1 AS id, %2 AS label";
355 $order = "ORDER BY %2";
357 // Use machine name instead of label in validate context
358 if ($context == 'validate') {
359 if (!empty($pseudoconstant['nameColumn'])) {
360 $params['labelColumn'] = $pseudoconstant['nameColumn'];
362 elseif (in_array('name', $availableFields)) {
363 $params['labelColumn'] = 'name';
366 // Condition param can be passed as an sql clause string or an array of clauses
367 if (!empty($params['condition'])) {
368 $wheres[] = implode(' AND ', (array) $params['condition']);
370 // onlyActive param will automatically filter on common flags
371 if (!empty($params['onlyActive'])) {
372 foreach (array('is_active' => 1, 'is_deleted' => 0, 'is_test' => 0) as $flag => $val) {
373 if (in_array($flag, $availableFields)) {
374 $wheres[] = "$flag = $val";
378 // Filter domain specific options
379 if (in_array('domain_id', $availableFields)) {
380 $wheres[] = 'domain_id = ' . CRM_Core_Config
::domainID();
382 $queryParams = array(
383 1 => array($params['keyColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
384 2 => array($params['labelColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
385 3 => array($pseudoconstant['table'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
387 // Add orderColumn param
388 if (!empty($params['orderColumn'])) {
389 $queryParams[4] = array($params['orderColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
);
390 $order = "ORDER BY %4";
392 // Support no sorting if $params[orderColumn] is FALSE
393 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
396 // Default to 'weight' if that column exists
397 elseif (in_array('weight', $availableFields)) {
398 $order = "ORDER BY weight";
402 $query = "$select $from";
404 $query .= " WHERE " . implode($wheres, ' AND ');
406 $query .= ' ' . $order;
407 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
408 while ($dao->fetch()) {
409 $output[$dao->id
] = $dao->label
;
413 if (!empty($params['localize']) ||
$pseudoconstant['table'] == 'civicrm_country' ||
$pseudoconstant['table'] == 'civicrm_state_province') {
414 $I18nParams = array();
415 if ($pseudoconstant['table'] == 'civicrm_country') {
416 $I18nParams['context'] = 'country';
418 if ($pseudoconstant['table'] == 'civicrm_state_province') {
419 $I18nParams['context'] = 'province';
421 $i18n = CRM_Core_I18n
::singleton();
422 $i18n->localizeArray($output, $I18nParams);
423 // Maintain sort by label
424 if ($order == "ORDER BY %2") {
425 CRM_Utils_Array
::asort($output);
428 self
::$cache[$cacheKey] = $output;
430 return $flip ?
array_flip($output) : $output;
434 // Return "Yes" and "No" for boolean fields
435 elseif (CRM_Utils_Array
::value('type', $fieldSpec) === CRM_Utils_Type
::T_BOOLEAN
) {
436 $output = $context == 'validate' ?
array(0, 1) : array(1 => ts('Yes'), 0 => ts('No'));
437 return $flip ?
array_flip($output) : $output;
439 // If we're still here, it's an error. Return FALSE.
444 * Fetch the translated label for a field given its key
446 * @param string $baoName
447 * @param string $fieldName
448 * @param string|Int $key
450 * TODO: Accept multivalued input?
452 * @return bool|null|string
453 * FALSE if the given field has no associated option list
454 * NULL if the given key has no corresponding option
455 * String if label is found
457 public static function getLabel($baoName, $fieldName, $key) {
458 $values = $baoName::buildOptions($fieldName, 'get');
459 if ($values === FALSE) {
462 return CRM_Utils_Array
::value($key, $values);
466 * Fetch the machine name for a field given its key
468 * @param string $baoName
469 * @param string $fieldName
470 * @param string|Int $key
472 * @return bool|null|string
473 * FALSE if the given field has no associated option list
474 * NULL if the given key has no corresponding option
475 * String if label is found
477 public static function getName($baoName, $fieldName, $key) {
478 $values = $baoName::buildOptions($fieldName, 'validate');
479 if ($values === FALSE) {
482 return CRM_Utils_Array
::value($key, $values);
486 * Fetch the key for a field option given its name
488 * @param string $baoName
489 * @param string $fieldName
490 * @param string|Int $value
492 * @return bool|null|string|number
493 * FALSE if the given field has no associated option list
494 * NULL if the given key has no corresponding option
495 * String|Number if key is found
497 public static function getKey($baoName, $fieldName, $value) {
498 $values = $baoName::buildOptions($fieldName, 'validate');
499 if ($values === FALSE) {
502 return CRM_Utils_Array
::key($value, $values);
506 * Lookup the admin page at which a field's option list can be edited
508 * @return string|null
510 public static function getOptionEditUrl($fieldSpec) {
511 // If it's an option group, that's easy
512 if (!empty($fieldSpec['pseudoconstant']['optionGroupName'])) {
513 return 'civicrm/admin/options/' . $fieldSpec['pseudoconstant']['optionGroupName'];
515 // For everything else...
516 elseif (!empty($fieldSpec['pseudoconstant']['table'])) {
517 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($fieldSpec['pseudoconstant']['table']);
521 // We don't have good mapping so have to do a bit of guesswork from the menu
522 list(, $parent, , $child) = explode('_', $daoName);
523 $sql = "SELECT path FROM civicrm_menu
524 WHERE page_callback LIKE '%CRM_Admin_Page_$child%' OR page_callback LIKE '%CRM_{$parent}_Page_$child%'
525 ORDER BY page_callback
527 return CRM_Core_Dao
::singleValueQuery($sql);
533 * DEPRECATED generic populate method
534 * All pseudoconstant functions that use this method are also @deprecated
536 * The static array $var is populated from the db
537 * using the <b>$name DAO</b>.
539 * Note: any database errors will be trapped by the DAO.
542 * The associative array we will fill.
543 * @param string $name
544 * The name of the DAO.
546 * Get all objects. default is to get only active ones.
547 * @param string $retrieve
548 * The field that we are interested in (normally name, differs in some objects).
549 * @param string $filter
550 * The field that we want to filter the result set with.
551 * @param string $condition
552 * The condition that gets passed to the final query as the WHERE clause.
554 * @param null $orderby
561 public static function populate(
566 $filter = 'is_active',
572 $cacheKey = "CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}";
573 $cache = CRM_Utils_Cache
::singleton();
574 $var = $cache->get($cacheKey);
575 if ($var && empty($force)) {
579 $object = new $name ();
581 $object->selectAdd();
582 $object->selectAdd("$key, $retrieve");
584 $object->whereAdd($condition);
588 $object->orderBy($retrieve);
591 $object->orderBy($orderby);
595 $object->$filter = 1;
600 while ($object->fetch()) {
601 $var[$object->$key] = $object->$retrieve;
604 $cache->set($cacheKey, $var);
608 * Flush given pseudoconstant so it can be reread from db
609 * nex time it's requested.
613 * @param bool|string $name pseudoconstant to be flushed
615 public static function flush($name = 'cache') {
616 if (isset(self
::$
$name)) {
619 if ($name == 'cache') {
620 CRM_Core_OptionGroup
::flushAll();
625 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
627 * Get all Activty types.
629 * The static array activityType is returned
633 * @return array - array reference of all activity types.
635 public static function &activityType() {
636 $args = func_get_args();
637 $all = CRM_Utils_Array
::value(0, $args, TRUE);
638 $includeCaseActivities = CRM_Utils_Array
::value(1, $args, FALSE);
639 $reset = CRM_Utils_Array
::value(2, $args, FALSE);
640 $returnColumn = CRM_Utils_Array
::value(3, $args, 'label');
641 $includeCampaignActivities = CRM_Utils_Array
::value(4, $args, FALSE);
642 $onlyComponentActivities = CRM_Utils_Array
::value(5, $args, FALSE);
643 $index = (int) $all . '_' . $returnColumn . '_' . (int) $includeCaseActivities;
644 $index .= '_' . (int) $includeCampaignActivities;
645 $index .= '_' . (int) $onlyComponentActivities;
647 if (NULL === self
::$activityType) {
648 self
::$activityType = array();
651 if (!isset(self
::$activityType[$index]) ||
$reset) {
654 $condition = 'AND filter = 0';
656 $componentClause = " v.component_id IS NULL";
657 if ($onlyComponentActivities) {
658 $componentClause = " v.component_id IS NOT NULL";
661 $componentIds = array();
662 $compInfo = CRM_Core_Component
::getEnabledComponents();
664 // build filter for listing activity types only if their
665 // respective components are enabled
666 foreach ($compInfo as $compName => $compObj) {
667 if ($compName == 'CiviCase') {
668 if ($includeCaseActivities) {
669 $componentIds[] = $compObj->componentID
;
672 elseif ($compName == 'CiviCampaign') {
673 if ($includeCampaignActivities) {
674 $componentIds[] = $compObj->componentID
;
678 $componentIds[] = $compObj->componentID
;
682 if (count($componentIds)) {
683 $componentIds = implode(',', $componentIds);
684 $componentClause = " ($componentClause OR v.component_id IN ($componentIds))";
685 if ($onlyComponentActivities) {
686 $componentClause = " ( v.component_id IN ($componentIds ) )";
689 $condition = $condition . ' AND ' . $componentClause;
691 self
::$activityType[$index] = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
693 return self
::$activityType[$index];
697 * Get all the State/Province from database.
699 * The static array stateProvince is returned, and if it's
700 * called the first time, the <b>State Province DAO</b> is used
701 * to get all the States.
703 * Note: any database errors will be trapped by the DAO.
707 * @param bool|int $id - Optional id to return
711 * @return array - array reference of all State/Provinces.
713 public static function &stateProvince($id = FALSE, $limit = TRUE) {
714 if (($id && !CRM_Utils_Array
::value($id, self
::$stateProvince)) ||
!self
::$stateProvince ||
!$id) {
715 $whereClause = FALSE;
716 $config = CRM_Core_Config
::singleton();
718 $countryIsoCodes = self
::countryIsoCode();
719 $limitCodes = $config->provinceLimit();
721 foreach ($limitCodes as $code) {
722 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
724 if (!empty($limitIds)) {
725 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
728 $whereClause = FALSE;
731 self
::populate(self
::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
733 // localise the province names if in an non-en_US locale
735 if ($tsLocale != '' and $tsLocale != 'en_US') {
736 $i18n = CRM_Core_I18n
::singleton();
737 $i18n->localizeArray(self
::$stateProvince, array(
738 'context' => 'province',
740 self
::$stateProvince = CRM_Utils_Array
::asort(self
::$stateProvince);
744 if (array_key_exists($id, self
::$stateProvince)) {
745 return self
::$stateProvince[$id];
752 return self
::$stateProvince;
756 * Get all the State/Province abbreviations from the database.
758 * Same as above, except gets the abbreviations instead of the names.
762 * @param bool|int $id - Optional id to return
766 * @return array - array reference of all State/Province abbreviations.
768 public static function &stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
772 FROM civicrm_state_province
780 return CRM_Core_DAO
::singleValueQuery($query, $params);
783 if (!self
::$stateProvinceAbbreviation ||
!$id) {
785 $whereClause = FALSE;
788 $config = CRM_Core_Config
::singleton();
789 $countryIsoCodes = self
::countryIsoCode();
790 $limitCodes = $config->provinceLimit();
792 foreach ($limitCodes as $code) {
793 $tmpArray = array_keys($countryIsoCodes, $code);
795 if (!empty($tmpArray)) {
796 $limitIds[] = array_shift($tmpArray);
799 if (!empty($limitIds)) {
800 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
803 self
::populate(self
::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
807 if (array_key_exists($id, self
::$stateProvinceAbbreviation)) {
808 return self
::$stateProvinceAbbreviation[$id];
815 return self
::$stateProvinceAbbreviation;
819 * Get all the countries from database.
821 * The static array country is returned, and if it's
822 * called the first time, the <b>Country DAO</b> is used
823 * to get all the countries.
825 * Note: any database errors will be trapped by the DAO.
829 * @param bool|int $id - Optional id to return
831 * @param bool $applyLimit
833 * @return array - array reference of all countries.
835 public static function country($id = FALSE, $applyLimit = TRUE) {
836 if (($id && !CRM_Utils_Array
::value($id, self
::$country)) ||
!self
::$country ||
!$id) {
838 $config = CRM_Core_Config
::singleton();
839 $limitCodes = array();
842 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
843 // (ensuring it's a subset of the legal values)
844 // K/P: We need to fix this, i dont think it works with new setting files
845 $limitCodes = $config->countryLimit();
846 if (!is_array($limitCodes)) {
848 $config->countryLimit
=> 1,
852 $limitCodes = array_intersect(self
::countryIsoCode(), $limitCodes);
855 if (count($limitCodes)) {
856 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
862 self
::populate(self
::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
864 // if default country is set, percolate it to the top
865 if ($config->defaultContactCountry()) {
866 $countryIsoCodes = self
::countryIsoCode();
867 $defaultID = array_search($config->defaultContactCountry(), $countryIsoCodes);
868 if ($defaultID !== FALSE) {
869 $default[$defaultID] = CRM_Utils_Array
::value($defaultID, self
::$country);
870 self
::$country = $default + self
::$country;
874 // localise the country names if in an non-en_US locale
876 if ($tsLocale != '' and $tsLocale != 'en_US') {
877 $i18n = CRM_Core_I18n
::singleton();
878 $i18n->localizeArray(self
::$country, array(
879 'context' => 'country',
881 self
::$country = CRM_Utils_Array
::asort(self
::$country);
885 if (array_key_exists($id, self
::$country)) {
886 return self
::$country[$id];
889 return CRM_Core_DAO
::$_nullObject;
892 return self
::$country;
896 * Get all the country ISO Code abbreviations from the database.
898 * The static array countryIsoCode is returned, and if it's
899 * called the first time, the <b>Country DAO</b> is used
900 * to get all the countries' ISO codes.
902 * Note: any database errors will be trapped by the DAO.
908 * @return array - array reference of all country ISO codes.
910 public static function &countryIsoCode($id = FALSE) {
911 if (!self
::$countryIsoCode) {
912 self
::populate(self
::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
915 if (array_key_exists($id, self
::$countryIsoCode)) {
916 return self
::$countryIsoCode[$id];
919 return CRM_Core_DAO
::$_nullObject;
922 return self
::$countryIsoCode;
926 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
928 * Get all groups from database
930 * The static array group is returned, and if it's
931 * called the first time, the <b>Group DAO</b> is used
932 * to get all the groups.
934 * Note: any database errors will be trapped by the DAO.
936 * @param string $groupType
937 * Type of group(Access/Mailing).
938 * @param bool $excludeHidden
939 * Exclude hidden groups.
943 * @return array - array reference of all groups.
945 public static function &allGroup($groupType = NULL, $excludeHidden = TRUE) {
946 $condition = CRM_Contact_BAO_Group
::groupTypeCondition($groupType, $excludeHidden);
949 self
::$group = array();
952 $groupKey = $groupType ?
$groupType : 'null';
954 if (!isset(self
::$group[$groupKey])) {
955 self
::$group[$groupKey] = NULL;
956 self
::populate(self
::$group[$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
958 return self
::$group[$groupKey];
962 * Create or get groups iterator (iterates over nested groups in a
965 * The GroupNesting instance is returned; it's created if this is being
966 * called for the first time
971 * @param bool $styledLabels
973 * @return mixed - instance of CRM_Contact_BAO_GroupNesting
975 public static function &groupIterator($styledLabels = FALSE) {
976 if (!self
::$groupIterator) {
978 When used as an object, GroupNesting implements Iterator
979 and iterates nested groups in a logical manner for us
981 self
::$groupIterator = new CRM_Contact_BAO_GroupNesting($styledLabels);
983 return self
::$groupIterator;
987 * Get all permissioned groups from database
989 * The static array group is returned, and if it's
990 * called the first time, the <b>Group DAO</b> is used
991 * to get all the groups.
993 * Note: any database errors will be trapped by the DAO.
995 * @param string $groupType
996 * Type of group(Access/Mailing).
997 * @param bool $excludeHidden
998 * Exclude hidden groups.
1002 * @return array - array reference of all groups.
1004 public static function group($groupType = NULL, $excludeHidden = TRUE) {
1005 return CRM_Core_Permission
::group($groupType, $excludeHidden);
1009 * Fetch groups in a nested format suitable for use in select form element
1010 * @param bool $checkPermissions
1011 * @param string|null $groupType
1012 * @param bool $excludeHidden
1015 public static function nestedGroup($checkPermissions = TRUE, $groupType = NULL, $excludeHidden = TRUE) {
1016 $groups = $checkPermissions ? self
::group($groupType, $excludeHidden) : self
::allGroup($groupType, $excludeHidden);
1017 return CRM_Contact_BAO_Group
::getGroupsHierarchy($groups, NULL, ' ', TRUE);
1021 * Get all permissioned groups from database
1023 * The static array group is returned, and if it's
1024 * called the first time, the <b>Group DAO</b> is used
1025 * to get all the groups.
1027 * Note: any database errors will be trapped by the DAO.
1031 * @param bool $onlyPublic
1032 * @param null $groupType
1033 * @param bool $excludeHidden
1035 * @return array - array reference of all groups.
1037 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
1038 if (!self
::$staticGroup) {
1039 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
1041 $condition .= " AND visibility != 'User and User Admin Only'";
1045 $condition .= ' AND ' . CRM_Contact_BAO_Group
::groupTypeCondition($groupType);
1048 if ($excludeHidden) {
1049 $condition .= ' AND is_hidden != 1 ';
1052 self
::populate(self
::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
1055 return self
::$staticGroup;
1059 * Get all Relationship Types from database.
1061 * The static array group is returned, and if it's
1062 * called the first time, the <b>RelationshipType DAO</b> is used
1063 * to get all the relationship types.
1065 * Note: any database errors will be trapped by the DAO.
1067 * @param string $valueColumnName
1068 * Db column name/label.
1069 * @param bool $reset
1070 * Reset relationship types if true.
1074 * @return array - array reference of all relationship types.
1076 public static function &relationshipType($valueColumnName = 'label', $reset = FALSE) {
1077 if (!CRM_Utils_Array
::value($valueColumnName, self
::$relationshipType) ||
$reset) {
1078 self
::$relationshipType[$valueColumnName] = array();
1080 //now we have name/label columns CRM-3336
1081 $column_a_b = "{$valueColumnName}_a_b";
1082 $column_b_a = "{$valueColumnName}_b_a";
1084 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1085 $relationshipTypeDAO->selectAdd();
1086 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1087 $relationshipTypeDAO->is_active
= 1;
1088 $relationshipTypeDAO->find();
1089 while ($relationshipTypeDAO->fetch()) {
1091 self
::$relationshipType[$valueColumnName][$relationshipTypeDAO->id
] = array(
1092 'id' => $relationshipTypeDAO->id
,
1093 $column_a_b => $relationshipTypeDAO->$column_a_b,
1094 $column_b_a => $relationshipTypeDAO->$column_b_a,
1095 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1096 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1097 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1098 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1103 return self
::$relationshipType[$valueColumnName];
1107 * Get all the ISO 4217 currency codes
1109 * so far, we use this for validation only, so there's no point of putting this into the database
1112 * @return array - array reference of all currency codes
1115 public static function ¤cyCode() {
1116 if (!self
::$currencyCode) {
1117 self
::$currencyCode = array(
1387 return self
::$currencyCode;
1391 * Get all the County from database.
1393 * The static array county is returned, and if it's
1394 * called the first time, the <b>County DAO</b> is used
1395 * to get all the Counties.
1397 * Note: any database errors will be trapped by the DAO.
1401 * @param bool|int $id - Optional id to return
1403 * @return array - array reference of all Counties
1405 public static function &county($id = FALSE) {
1406 if (!self
::$county) {
1408 $config = CRM_Core_Config
::singleton();
1409 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1410 self
::populate(self
::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1413 if (array_key_exists($id, self
::$county)) {
1414 return self
::$county[$id];
1417 return CRM_Core_DAO
::$_nullObject;
1420 return self
::$county;
1424 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1425 * Get all active payment processors
1427 * The static array paymentProcessor is returned
1432 * Get payment processors - default is to get only active ones.
1434 * Get test payment processors.
1436 * @param null $additionalCond
1438 * @return array - array of all payment processors
1440 public static function &paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1441 $condition = "is_test = ";
1442 $condition .= ($test) ?
'1' : '0';
1444 if ($additionalCond) {
1445 $condition .= " AND ( $additionalCond ) ";
1448 // CRM-7178. Make sure we only include payment processors valid in ths
1450 $condition .= " AND domain_id = " . CRM_Core_Config
::domainID();
1452 $cacheKey = $condition . '_' . (int) $all;
1453 if (!isset(self
::$paymentProcessor[$cacheKey])) {
1454 self
::populate(self
::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1457 return self
::$paymentProcessor[$cacheKey];
1461 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1463 * The static array paymentProcessorType is returned
1468 * Get payment processors - default is to get only active ones.
1471 * @param string $return
1473 * @return array - array of all payment processor types
1475 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1476 $cacheKey = $id . '_' . $return;
1477 if (empty(self
::$paymentProcessorType[$cacheKey])) {
1478 self
::populate(self
::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1480 if ($id && CRM_Utils_Array
::value($id, self
::$paymentProcessorType[$cacheKey])) {
1481 return self
::$paymentProcessorType[$cacheKey][$id];
1483 return self
::$paymentProcessorType[$cacheKey];
1487 * Get all the World Regions from Database
1492 * @return array - array reference of all World Regions
1495 public static function &worldRegion($id = FALSE) {
1496 if (!self
::$worldRegions) {
1497 self
::populate(self
::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1501 if (array_key_exists($id, self
::$worldRegions)) {
1502 return self
::$worldRegions[$id];
1505 return CRM_Core_DAO
::$_nullObject;
1509 return self
::$worldRegions;
1513 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1515 * Get all Activity Statuses.
1517 * The static array activityStatus is returned
1521 * @param string $column
1523 * @return array - array reference of all activity statuses
1525 public static function &activityStatus($column = 'label') {
1526 if (NULL === self
::$activityStatus) {
1527 self
::$activityStatus = array();
1529 if (!array_key_exists($column, self
::$activityStatus)) {
1530 self
::$activityStatus[$column] = array();
1532 self
::$activityStatus[$column] = CRM_Core_OptionGroup
::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1535 return self
::$activityStatus[$column];
1539 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1541 * Get all Visibility levels.
1543 * The static array visibility is returned
1547 * @param string $column
1549 * @return array - array reference of all Visibility levels.
1551 public static function &visibility($column = 'label') {
1552 if (!isset(self
::$visibility)) {
1553 self
::$visibility = array();
1556 if (!isset(self
::$visibility[$column])) {
1557 self
::$visibility[$column] = CRM_Core_OptionGroup
::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1560 return self
::$visibility[$column];
1564 * @param int $countryID
1565 * @param string $field
1569 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1570 static $_cache = NULL;
1572 $cacheKey = "{$countryID}_{$field}";
1577 if (!empty($_cache[$cacheKey])) {
1578 return $_cache[$cacheKey];
1582 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1583 FROM civicrm_state_province
1584 WHERE country_id = %1
1593 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1596 while ($dao->fetch()) {
1597 $result[$dao->id
] = $dao->name
;
1600 // localise the stateProvince names if in an non-en_US locale
1601 $config = CRM_Core_Config
::singleton();
1603 if ($tsLocale != '' and $tsLocale != 'en_US') {
1604 $i18n = CRM_Core_I18n
::singleton();
1605 $i18n->localizeArray($result, array(
1606 'context' => 'province',
1608 $result = CRM_Utils_Array
::asort($result);
1611 $_cache[$cacheKey] = $result;
1613 CRM_Utils_Hook
::buildStateProvinceForCountry($countryID, $result);
1619 * @param int $stateID
1623 public static function &countyForState($stateID) {
1624 if (is_array($stateID)) {
1625 $states = implode(", ", $stateID);
1627 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1629 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1630 WHERE civicrm_county.state_province_id in ( $states )
1631 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1633 $dao = CRM_Core_DAO
::executeQuery($query);
1636 while ($dao->fetch()) {
1637 $result[$dao->id
] = $dao->abbreviation
. ': ' . $dao->name
;
1642 static $_cache = NULL;
1644 $cacheKey = "{$stateID}_name";
1649 if (!empty($_cache[$cacheKey])) {
1650 return $_cache[$cacheKey];
1654 SELECT civicrm_county.name name, civicrm_county.id id
1656 WHERE state_province_id = %1
1665 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1668 while ($dao->fetch()) {
1669 $result[$dao->id
] = $dao->name
;
1677 * Given a state ID return the country ID, this allows
1678 * us to populate forms and values for downstream code
1680 * @param int $stateID
1682 * @return int the country id that the state belongs to
1685 public static function countryIDForStateID($stateID) {
1686 if (empty($stateID)) {
1687 return CRM_Core_DAO
::$_nullObject;
1692 FROM civicrm_state_province
1695 $params = array(1 => array($stateID, 'Integer'));
1697 return CRM_Core_DAO
::singleValueQuery($query, $params);
1701 * Get all types of Greetings.
1703 * The static array of greeting is returned
1708 * Get All Email Greetings - default is to get only active ones.
1710 * @param string $columnName
1712 * @return array - array reference of all greetings.
1714 public static function greeting($filter, $columnName = 'label') {
1715 $index = $filter['greeting_type'] . '_' . $columnName;
1717 // also add contactType to the array
1718 $contactType = CRM_Utils_Array
::value('contact_type', $filter);
1720 $index .= '_' . $contactType;
1723 if (NULL === self
::$greeting) {
1724 self
::$greeting = array();
1727 if (!CRM_Utils_Array
::value($index, self
::$greeting)) {
1728 $filterCondition = NULL;
1730 $filterVal = 'v.filter =';
1731 switch ($contactType) {
1740 case 'Organization':
1744 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1747 self
::$greeting[$index] = CRM_Core_OptionGroup
::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1750 return self
::$greeting[$index];
1754 * Construct array of default greeting values for contact type
1758 * @return array - array reference of default greetings.
1761 public static function &greetingDefaults() {
1762 if (!self
::$greetingDefaults) {
1763 $defaultGreetings = array();
1764 $contactTypes = self
::get('CRM_Contact_DAO_Contact', 'contact_type', array('keyColumn' => 'id', 'labelColumn' => 'name'));
1766 foreach ($contactTypes as $filter => $contactType) {
1767 $filterCondition = " AND (v.filter = 0 OR v.filter = $filter) AND v.is_default = 1 ";
1769 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1770 $tokenVal = CRM_Core_OptionGroup
::values($greeting, NULL, NULL, NULL, $filterCondition, 'label');
1771 $defaultGreetings[$contactType][$greeting] = $tokenVal;
1775 self
::$greetingDefaults = $defaultGreetings;
1778 return self
::$greetingDefaults;
1782 * Get all extensions
1784 * The static array extensions
1786 * FIXME: This is called by civix but not by any core code. We
1787 * should provide an API call which civix can use instead.
1791 * @return array - array($fullyQualifiedName => $label) list of extensions
1793 public static function &getExtensions() {
1794 if (!self
::$extensions) {
1795 self
::$extensions = array();
1797 SELECT full_name, label
1798 FROM civicrm_extension
1801 $dao = CRM_Core_DAO
::executeQuery($sql);
1802 while ($dao->fetch()) {
1803 self
::$extensions[$dao->full_name
] = $dao->label
;
1807 return self
::$extensions;
1811 * Get all options values
1813 * The static array option values is returned
1817 * @param bool $optionGroupName
1818 * Get All Option Group values- default is to get only active ones.
1821 * @param null $condition
1823 * @return array - array reference of all Option Group Name
1825 public static function accountOptionValues($optionGroupName, $id = NULL, $condition = NULL) {
1826 $cacheKey = $optionGroupName . '_' . $condition;
1827 if (empty(self
::$accountOptionValues[$cacheKey])) {
1828 self
::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup
::values($optionGroupName, FALSE, FALSE, FALSE, $condition);
1831 return CRM_Utils_Array
::value($id, self
::$accountOptionValues[$cacheKey]);
1834 return self
::$accountOptionValues[$cacheKey];
1838 * Fetch the list of active extensions of type 'module'
1840 * @param bool $fresh
1841 * Whether to forcibly reload extensions list from canonical store.
1844 * @return array - array(array('prefix' => $, 'file' => $))
1846 public static function getModuleExtensions($fresh = FALSE) {
1847 return CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles($fresh);
1854 * The static array tax rates is returned
1858 * @return array - array list of tax rates with the financial type
1860 public static function getTaxRates() {
1861 if (!self
::$taxRates) {
1862 self
::$taxRates = array();
1864 SELECT fa.tax_rate, efa.entity_id
1865 FROM civicrm_entity_financial_account efa
1866 INNER JOIN civicrm_financial_account fa ON fa.id = efa.financial_account_id
1867 INNER JOIN civicrm_option_value cov ON cov.value = efa.account_relationship
1868 INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id
1869 WHERE efa.entity_table = 'civicrm_financial_type'
1870 AND cov.name = 'Sales Tax Account is'
1871 AND cog.name = 'account_relationship'
1872 AND fa.is_active = 1";
1873 $dao = CRM_Core_DAO
::executeQuery($sql);
1874 while ($dao->fetch()) {
1875 self
::$taxRates[$dao->entity_id
] = $dao->tax_rate
;
1879 return self
::$taxRates;