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
634 * array reference of all activity types.
636 public static function &activityType() {
637 $args = func_get_args();
638 $all = CRM_Utils_Array
::value(0, $args, TRUE);
639 $includeCaseActivities = CRM_Utils_Array
::value(1, $args, FALSE);
640 $reset = CRM_Utils_Array
::value(2, $args, FALSE);
641 $returnColumn = CRM_Utils_Array
::value(3, $args, 'label');
642 $includeCampaignActivities = CRM_Utils_Array
::value(4, $args, FALSE);
643 $onlyComponentActivities = CRM_Utils_Array
::value(5, $args, FALSE);
644 $index = (int) $all . '_' . $returnColumn . '_' . (int) $includeCaseActivities;
645 $index .= '_' . (int) $includeCampaignActivities;
646 $index .= '_' . (int) $onlyComponentActivities;
648 if (NULL === self
::$activityType) {
649 self
::$activityType = array();
652 if (!isset(self
::$activityType[$index]) ||
$reset) {
655 $condition = 'AND filter = 0';
657 $componentClause = " v.component_id IS NULL";
658 if ($onlyComponentActivities) {
659 $componentClause = " v.component_id IS NOT NULL";
662 $componentIds = array();
663 $compInfo = CRM_Core_Component
::getEnabledComponents();
665 // build filter for listing activity types only if their
666 // respective components are enabled
667 foreach ($compInfo as $compName => $compObj) {
668 if ($compName == 'CiviCase') {
669 if ($includeCaseActivities) {
670 $componentIds[] = $compObj->componentID
;
673 elseif ($compName == 'CiviCampaign') {
674 if ($includeCampaignActivities) {
675 $componentIds[] = $compObj->componentID
;
679 $componentIds[] = $compObj->componentID
;
683 if (count($componentIds)) {
684 $componentIds = implode(',', $componentIds);
685 $componentClause = " ($componentClause OR v.component_id IN ($componentIds))";
686 if ($onlyComponentActivities) {
687 $componentClause = " ( v.component_id IN ($componentIds ) )";
690 $condition = $condition . ' AND ' . $componentClause;
692 self
::$activityType[$index] = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
694 return self
::$activityType[$index];
698 * Get all the State/Province from database.
700 * The static array stateProvince is returned, and if it's
701 * called the first time, the <b>State Province DAO</b> is used
702 * to get all the States.
704 * Note: any database errors will be trapped by the DAO.
708 * @param bool|int $id - Optional id to return
713 * array reference of all State/Provinces.
715 public static function &stateProvince($id = FALSE, $limit = TRUE) {
716 if (($id && !CRM_Utils_Array
::value($id, self
::$stateProvince)) ||
!self
::$stateProvince ||
!$id) {
717 $whereClause = FALSE;
718 $config = CRM_Core_Config
::singleton();
720 $countryIsoCodes = self
::countryIsoCode();
721 $limitCodes = $config->provinceLimit();
723 foreach ($limitCodes as $code) {
724 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
726 if (!empty($limitIds)) {
727 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
730 $whereClause = FALSE;
733 self
::populate(self
::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
735 // localise the province names if in an non-en_US locale
737 if ($tsLocale != '' and $tsLocale != 'en_US') {
738 $i18n = CRM_Core_I18n
::singleton();
739 $i18n->localizeArray(self
::$stateProvince, array(
740 'context' => 'province',
742 self
::$stateProvince = CRM_Utils_Array
::asort(self
::$stateProvince);
746 if (array_key_exists($id, self
::$stateProvince)) {
747 return self
::$stateProvince[$id];
754 return self
::$stateProvince;
758 * Get all the State/Province abbreviations from the database.
760 * Same as above, except gets the abbreviations instead of the names.
764 * @param bool|int $id - Optional id to return
769 * array reference of all State/Province abbreviations.
771 public static function &stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
775 FROM civicrm_state_province
783 return CRM_Core_DAO
::singleValueQuery($query, $params);
786 if (!self
::$stateProvinceAbbreviation ||
!$id) {
788 $whereClause = FALSE;
791 $config = CRM_Core_Config
::singleton();
792 $countryIsoCodes = self
::countryIsoCode();
793 $limitCodes = $config->provinceLimit();
795 foreach ($limitCodes as $code) {
796 $tmpArray = array_keys($countryIsoCodes, $code);
798 if (!empty($tmpArray)) {
799 $limitIds[] = array_shift($tmpArray);
802 if (!empty($limitIds)) {
803 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
806 self
::populate(self
::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
810 if (array_key_exists($id, self
::$stateProvinceAbbreviation)) {
811 return self
::$stateProvinceAbbreviation[$id];
818 return self
::$stateProvinceAbbreviation;
822 * Get all the countries from database.
824 * The static array country is returned, and if it's
825 * called the first time, the <b>Country DAO</b> is used
826 * to get all the countries.
828 * Note: any database errors will be trapped by the DAO.
832 * @param bool|int $id - Optional id to return
834 * @param bool $applyLimit
837 * array reference of all countries.
839 public static function country($id = FALSE, $applyLimit = TRUE) {
840 if (($id && !CRM_Utils_Array
::value($id, self
::$country)) ||
!self
::$country ||
!$id) {
842 $config = CRM_Core_Config
::singleton();
843 $limitCodes = array();
846 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
847 // (ensuring it's a subset of the legal values)
848 // K/P: We need to fix this, i dont think it works with new setting files
849 $limitCodes = $config->countryLimit();
850 if (!is_array($limitCodes)) {
852 $config->countryLimit
=> 1,
856 $limitCodes = array_intersect(self
::countryIsoCode(), $limitCodes);
859 if (count($limitCodes)) {
860 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
866 self
::populate(self
::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
868 // if default country is set, percolate it to the top
869 if ($config->defaultContactCountry()) {
870 $countryIsoCodes = self
::countryIsoCode();
871 $defaultID = array_search($config->defaultContactCountry(), $countryIsoCodes);
872 if ($defaultID !== FALSE) {
873 $default[$defaultID] = CRM_Utils_Array
::value($defaultID, self
::$country);
874 self
::$country = $default + self
::$country;
878 // localise the country names if in an non-en_US locale
880 if ($tsLocale != '' and $tsLocale != 'en_US') {
881 $i18n = CRM_Core_I18n
::singleton();
882 $i18n->localizeArray(self
::$country, array(
883 'context' => 'country',
885 self
::$country = CRM_Utils_Array
::asort(self
::$country);
889 if (array_key_exists($id, self
::$country)) {
890 return self
::$country[$id];
893 return CRM_Core_DAO
::$_nullObject;
896 return self
::$country;
900 * Get all the country ISO Code abbreviations from the database.
902 * The static array countryIsoCode is returned, and if it's
903 * called the first time, the <b>Country DAO</b> is used
904 * to get all the countries' ISO codes.
906 * Note: any database errors will be trapped by the DAO.
913 * array reference of all country ISO codes.
915 public static function &countryIsoCode($id = FALSE) {
916 if (!self
::$countryIsoCode) {
917 self
::populate(self
::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
920 if (array_key_exists($id, self
::$countryIsoCode)) {
921 return self
::$countryIsoCode[$id];
924 return CRM_Core_DAO
::$_nullObject;
927 return self
::$countryIsoCode;
931 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
933 * Get all groups from database
935 * The static array group is returned, and if it's
936 * called the first time, the <b>Group DAO</b> is used
937 * to get all the groups.
939 * Note: any database errors will be trapped by the DAO.
941 * @param string $groupType
942 * Type of group(Access/Mailing).
943 * @param bool $excludeHidden
944 * Exclude hidden groups.
949 * array reference of all groups.
951 public static function &allGroup($groupType = NULL, $excludeHidden = TRUE) {
952 $condition = CRM_Contact_BAO_Group
::groupTypeCondition($groupType, $excludeHidden);
955 self
::$group = array();
958 $groupKey = $groupType ?
$groupType : 'null';
960 if (!isset(self
::$group[$groupKey])) {
961 self
::$group[$groupKey] = NULL;
962 self
::populate(self
::$group[$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
964 return self
::$group[$groupKey];
968 * Create or get groups iterator (iterates over nested groups in a
971 * The GroupNesting instance is returned; it's created if this is being
972 * called for the first time
977 * @param bool $styledLabels
979 * @return mixed - instance of CRM_Contact_BAO_GroupNesting
981 public static function &groupIterator($styledLabels = FALSE) {
982 if (!self
::$groupIterator) {
984 When used as an object, GroupNesting implements Iterator
985 and iterates nested groups in a logical manner for us
987 self
::$groupIterator = new CRM_Contact_BAO_GroupNesting($styledLabels);
989 return self
::$groupIterator;
993 * Get all permissioned groups from database
995 * The static array group is returned, and if it's
996 * called the first time, the <b>Group DAO</b> is used
997 * to get all the groups.
999 * Note: any database errors will be trapped by the DAO.
1001 * @param string $groupType
1002 * Type of group(Access/Mailing).
1003 * @param bool $excludeHidden
1004 * Exclude hidden groups.
1009 * array reference of all groups.
1011 public static function group($groupType = NULL, $excludeHidden = TRUE) {
1012 return CRM_Core_Permission
::group($groupType, $excludeHidden);
1016 * Fetch groups in a nested format suitable for use in select form element
1017 * @param bool $checkPermissions
1018 * @param string|null $groupType
1019 * @param bool $excludeHidden
1022 public static function nestedGroup($checkPermissions = TRUE, $groupType = NULL, $excludeHidden = TRUE) {
1023 $groups = $checkPermissions ? self
::group($groupType, $excludeHidden) : self
::allGroup($groupType, $excludeHidden);
1024 return CRM_Contact_BAO_Group
::getGroupsHierarchy($groups, NULL, ' ', TRUE);
1028 * Get all permissioned groups from database
1030 * The static array group is returned, and if it's
1031 * called the first time, the <b>Group DAO</b> is used
1032 * to get all the groups.
1034 * Note: any database errors will be trapped by the DAO.
1038 * @param bool $onlyPublic
1039 * @param null $groupType
1040 * @param bool $excludeHidden
1043 * array reference of all groups.
1045 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
1046 if (!self
::$staticGroup) {
1047 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
1049 $condition .= " AND visibility != 'User and User Admin Only'";
1053 $condition .= ' AND ' . CRM_Contact_BAO_Group
::groupTypeCondition($groupType);
1056 if ($excludeHidden) {
1057 $condition .= ' AND is_hidden != 1 ';
1060 self
::populate(self
::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
1063 return self
::$staticGroup;
1067 * Get all Relationship Types from database.
1069 * The static array group is returned, and if it's
1070 * called the first time, the <b>RelationshipType DAO</b> is used
1071 * to get all the relationship types.
1073 * Note: any database errors will be trapped by the DAO.
1075 * @param string $valueColumnName
1076 * Db column name/label.
1077 * @param bool $reset
1078 * Reset relationship types if true.
1083 * array reference of all relationship types.
1085 public static function &relationshipType($valueColumnName = 'label', $reset = FALSE) {
1086 if (!CRM_Utils_Array
::value($valueColumnName, self
::$relationshipType) ||
$reset) {
1087 self
::$relationshipType[$valueColumnName] = array();
1089 //now we have name/label columns CRM-3336
1090 $column_a_b = "{$valueColumnName}_a_b";
1091 $column_b_a = "{$valueColumnName}_b_a";
1093 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1094 $relationshipTypeDAO->selectAdd();
1095 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1096 $relationshipTypeDAO->is_active
= 1;
1097 $relationshipTypeDAO->find();
1098 while ($relationshipTypeDAO->fetch()) {
1100 self
::$relationshipType[$valueColumnName][$relationshipTypeDAO->id
] = array(
1101 'id' => $relationshipTypeDAO->id
,
1102 $column_a_b => $relationshipTypeDAO->$column_a_b,
1103 $column_b_a => $relationshipTypeDAO->$column_b_a,
1104 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1105 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1106 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1107 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1112 return self
::$relationshipType[$valueColumnName];
1116 * Get all the ISO 4217 currency codes
1118 * so far, we use this for validation only, so there's no point of putting this into the database
1122 * array reference of all currency codes
1125 public static function ¤cyCode() {
1126 if (!self
::$currencyCode) {
1127 self
::$currencyCode = array(
1397 return self
::$currencyCode;
1401 * Get all the County from database.
1403 * The static array county is returned, and if it's
1404 * called the first time, the <b>County DAO</b> is used
1405 * to get all the Counties.
1407 * Note: any database errors will be trapped by the DAO.
1411 * @param bool|int $id - Optional id to return
1414 * array reference of all Counties
1416 public static function &county($id = FALSE) {
1417 if (!self
::$county) {
1419 $config = CRM_Core_Config
::singleton();
1420 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1421 self
::populate(self
::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1424 if (array_key_exists($id, self
::$county)) {
1425 return self
::$county[$id];
1428 return CRM_Core_DAO
::$_nullObject;
1431 return self
::$county;
1435 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1436 * Get all active payment processors
1438 * The static array paymentProcessor is returned
1443 * Get payment processors - default is to get only active ones.
1445 * Get test payment processors.
1447 * @param null $additionalCond
1450 * array of all payment processors
1452 public static function &paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1453 $condition = "is_test = ";
1454 $condition .= ($test) ?
'1' : '0';
1456 if ($additionalCond) {
1457 $condition .= " AND ( $additionalCond ) ";
1460 // CRM-7178. Make sure we only include payment processors valid in ths
1462 $condition .= " AND domain_id = " . CRM_Core_Config
::domainID();
1464 $cacheKey = $condition . '_' . (int) $all;
1465 if (!isset(self
::$paymentProcessor[$cacheKey])) {
1466 self
::populate(self
::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1469 return self
::$paymentProcessor[$cacheKey];
1473 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1475 * The static array paymentProcessorType is returned
1480 * Get payment processors - default is to get only active ones.
1483 * @param string $return
1486 * array of all payment processor types
1488 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1489 $cacheKey = $id . '_' . $return;
1490 if (empty(self
::$paymentProcessorType[$cacheKey])) {
1491 self
::populate(self
::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1493 if ($id && CRM_Utils_Array
::value($id, self
::$paymentProcessorType[$cacheKey])) {
1494 return self
::$paymentProcessorType[$cacheKey][$id];
1496 return self
::$paymentProcessorType[$cacheKey];
1500 * Get all the World Regions from Database
1506 * array reference of all World Regions
1509 public static function &worldRegion($id = FALSE) {
1510 if (!self
::$worldRegions) {
1511 self
::populate(self
::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1515 if (array_key_exists($id, self
::$worldRegions)) {
1516 return self
::$worldRegions[$id];
1519 return CRM_Core_DAO
::$_nullObject;
1523 return self
::$worldRegions;
1527 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1529 * Get all Activity Statuses.
1531 * The static array activityStatus is returned
1535 * @param string $column
1538 * array reference of all activity statuses
1540 public static function &activityStatus($column = 'label') {
1541 if (NULL === self
::$activityStatus) {
1542 self
::$activityStatus = array();
1544 if (!array_key_exists($column, self
::$activityStatus)) {
1545 self
::$activityStatus[$column] = array();
1547 self
::$activityStatus[$column] = CRM_Core_OptionGroup
::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1550 return self
::$activityStatus[$column];
1554 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1556 * Get all Visibility levels.
1558 * The static array visibility is returned
1562 * @param string $column
1565 * array reference of all Visibility levels.
1567 public static function &visibility($column = 'label') {
1568 if (!isset(self
::$visibility)) {
1569 self
::$visibility = array();
1572 if (!isset(self
::$visibility[$column])) {
1573 self
::$visibility[$column] = CRM_Core_OptionGroup
::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1576 return self
::$visibility[$column];
1580 * @param int $countryID
1581 * @param string $field
1585 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1586 static $_cache = NULL;
1588 $cacheKey = "{$countryID}_{$field}";
1593 if (!empty($_cache[$cacheKey])) {
1594 return $_cache[$cacheKey];
1598 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1599 FROM civicrm_state_province
1600 WHERE country_id = %1
1609 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1612 while ($dao->fetch()) {
1613 $result[$dao->id
] = $dao->name
;
1616 // localise the stateProvince names if in an non-en_US locale
1617 $config = CRM_Core_Config
::singleton();
1619 if ($tsLocale != '' and $tsLocale != 'en_US') {
1620 $i18n = CRM_Core_I18n
::singleton();
1621 $i18n->localizeArray($result, array(
1622 'context' => 'province',
1624 $result = CRM_Utils_Array
::asort($result);
1627 $_cache[$cacheKey] = $result;
1629 CRM_Utils_Hook
::buildStateProvinceForCountry($countryID, $result);
1635 * @param int $stateID
1639 public static function &countyForState($stateID) {
1640 if (is_array($stateID)) {
1641 $states = implode(", ", $stateID);
1643 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1645 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1646 WHERE civicrm_county.state_province_id in ( $states )
1647 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1649 $dao = CRM_Core_DAO
::executeQuery($query);
1652 while ($dao->fetch()) {
1653 $result[$dao->id
] = $dao->abbreviation
. ': ' . $dao->name
;
1658 static $_cache = NULL;
1660 $cacheKey = "{$stateID}_name";
1665 if (!empty($_cache[$cacheKey])) {
1666 return $_cache[$cacheKey];
1670 SELECT civicrm_county.name name, civicrm_county.id id
1672 WHERE state_province_id = %1
1681 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1684 while ($dao->fetch()) {
1685 $result[$dao->id
] = $dao->name
;
1693 * Given a state ID return the country ID, this allows
1694 * us to populate forms and values for downstream code
1696 * @param int $stateID
1699 * the country id that the state belongs to
1702 public static function countryIDForStateID($stateID) {
1703 if (empty($stateID)) {
1704 return CRM_Core_DAO
::$_nullObject;
1709 FROM civicrm_state_province
1712 $params = array(1 => array($stateID, 'Integer'));
1714 return CRM_Core_DAO
::singleValueQuery($query, $params);
1718 * Get all types of Greetings.
1720 * The static array of greeting is returned
1725 * Get All Email Greetings - default is to get only active ones.
1727 * @param string $columnName
1730 * array reference of all greetings.
1732 public static function greeting($filter, $columnName = 'label') {
1733 $index = $filter['greeting_type'] . '_' . $columnName;
1735 // also add contactType to the array
1736 $contactType = CRM_Utils_Array
::value('contact_type', $filter);
1738 $index .= '_' . $contactType;
1741 if (NULL === self
::$greeting) {
1742 self
::$greeting = array();
1745 if (!CRM_Utils_Array
::value($index, self
::$greeting)) {
1746 $filterCondition = NULL;
1748 $filterVal = 'v.filter =';
1749 switch ($contactType) {
1758 case 'Organization':
1762 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1765 self
::$greeting[$index] = CRM_Core_OptionGroup
::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1768 return self
::$greeting[$index];
1772 * Construct array of default greeting values for contact type
1777 * array reference of default greetings.
1780 public static function &greetingDefaults() {
1781 if (!self
::$greetingDefaults) {
1782 $defaultGreetings = array();
1783 $contactTypes = self
::get('CRM_Contact_DAO_Contact', 'contact_type', array('keyColumn' => 'id', 'labelColumn' => 'name'));
1785 foreach ($contactTypes as $filter => $contactType) {
1786 $filterCondition = " AND (v.filter = 0 OR v.filter = $filter) AND v.is_default = 1 ";
1788 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1789 $tokenVal = CRM_Core_OptionGroup
::values($greeting, NULL, NULL, NULL, $filterCondition, 'label');
1790 $defaultGreetings[$contactType][$greeting] = $tokenVal;
1794 self
::$greetingDefaults = $defaultGreetings;
1797 return self
::$greetingDefaults;
1801 * Get all extensions
1803 * The static array extensions
1805 * FIXME: This is called by civix but not by any core code. We
1806 * should provide an API call which civix can use instead.
1811 * array($fullyQualifiedName => $label) list of extensions
1813 public static function &getExtensions() {
1814 if (!self
::$extensions) {
1815 self
::$extensions = array();
1817 SELECT full_name, label
1818 FROM civicrm_extension
1821 $dao = CRM_Core_DAO
::executeQuery($sql);
1822 while ($dao->fetch()) {
1823 self
::$extensions[$dao->full_name
] = $dao->label
;
1827 return self
::$extensions;
1831 * Get all options values
1833 * The static array option values is returned
1837 * @param bool $optionGroupName
1838 * Get All Option Group values- default is to get only active ones.
1841 * @param null $condition
1844 * array reference of all Option Group Name
1846 public static function accountOptionValues($optionGroupName, $id = NULL, $condition = NULL) {
1847 $cacheKey = $optionGroupName . '_' . $condition;
1848 if (empty(self
::$accountOptionValues[$cacheKey])) {
1849 self
::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup
::values($optionGroupName, FALSE, FALSE, FALSE, $condition);
1852 return CRM_Utils_Array
::value($id, self
::$accountOptionValues[$cacheKey]);
1855 return self
::$accountOptionValues[$cacheKey];
1859 * Fetch the list of active extensions of type 'module'
1861 * @param bool $fresh
1862 * Whether to forcibly reload extensions list from canonical store.
1866 * array(array('prefix' => $, 'file' => $))
1868 public static function getModuleExtensions($fresh = FALSE) {
1869 return CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles($fresh);
1876 * The static array tax rates is returned
1881 * array list of tax rates with the financial type
1883 public static function getTaxRates() {
1884 if (!self
::$taxRates) {
1885 self
::$taxRates = array();
1887 SELECT fa.tax_rate, efa.entity_id
1888 FROM civicrm_entity_financial_account efa
1889 INNER JOIN civicrm_financial_account fa ON fa.id = efa.financial_account_id
1890 INNER JOIN civicrm_option_value cov ON cov.value = efa.account_relationship
1891 INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id
1892 WHERE efa.entity_table = 'civicrm_financial_type'
1893 AND cov.name = 'Sales Tax Account is'
1894 AND cog.name = 'account_relationship'
1895 AND fa.is_active = 1";
1896 $dao = CRM_Core_DAO
::executeQuery($sql);
1897 while ($dao->fetch()) {
1898 self
::$taxRates[$dao->entity_id
] = $dao->tax_rate
;
1902 return self
::$taxRates;