3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
30 * Stores all constants and pseudo constants for CRM application.
32 * examples of constants are "Contact Type" which will always be either
33 * 'Individual', 'Household', 'Organization'.
35 * pseudo constants are entities from the database whose values rarely
36 * change. examples are list of countries, states, location types,
39 * currently we're getting the data from the underlying database. this
40 * will be reworked to use caching.
42 * Note: All pseudoconstants should be uninitialized or default to NULL.
43 * This provides greater consistency/predictability after flushing.
46 * @copyright CiviCRM LLC (c) 2004-2015
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 * NOTE: If someone undertakes a refactoring of this, please consider the use-case of
196 * the Setting.getoptions API. There is no DAO/field, but it would be nice to use the
197 * same 'pseudoconstant' struct in *.settings.php. This means loosening the coupling
198 * between $field lookup and the $pseudoconstant evaluation.
200 * @param string $daoName
201 * @param string $fieldName
202 * @param array $params
203 * - name string name of the option group
204 * - flip boolean results are return in id => label format if false
205 * if true, the results are reversed
206 * - grouping boolean if true, return the value in 'grouping' column (currently unsupported for tables other than option_value)
207 * - localize boolean if true, localize the results before returning
208 * - condition string|array add condition(s) to the sql query - will be concatenated using 'AND'
209 * - keyColumn string the column to use for 'id'
210 * - labelColumn string the column to use for 'label'
211 * - orderColumn string the column to use for sorting, defaults to 'weight' column if one exists, else defaults to labelColumn
212 * - onlyActive boolean return only the action option values
213 * - fresh boolean ignore cache entries and go back to DB
214 * @param string $context : Context string
217 * array on success, FALSE on error.
220 public static function get($daoName, $fieldName, $params = array(), $context = NULL) {
221 CRM_Core_DAO
::buildOptionsContext($context);
222 $flip = !empty($params['flip']);
223 // Merge params with defaults
227 'onlyActive' => ($context == 'validate' ||
$context == 'get') ?
FALSE : TRUE,
231 // Custom fields are not in the schema
232 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
233 $customField = new CRM_Core_DAO_CustomField();
234 $customField->id
= (int) substr($fieldName, 7);
235 $customField->find(TRUE);
238 if (!empty($customField->option_group_id
)) {
239 $options = CRM_Core_OptionGroup
::valuesByID($customField->option_group_id
,
243 // Note: for custom fields the 'name' column is NULL
244 CRM_Utils_Array
::value('labelColumn', $params, 'label'),
245 $params['onlyActive'],
250 if ($customField->data_type
=== 'StateProvince') {
251 $options = self
::stateProvince();
253 elseif ($customField->data_type
=== 'Country') {
254 $options = $context == 'validate' ? self
::countryIsoCode() : self
::country();
256 elseif ($customField->data_type
=== 'Boolean') {
257 $options = $context == 'validate' ?
array(0, 1) : CRM_Core_SelectValues
::boolean();
260 CRM_Utils_Hook
::customFieldOptions($customField->id
, $options, FALSE);
261 if ($options && $flip) {
262 $options = array_flip($options);
264 $customField->free();
268 // Core field: load schema
269 $dao = new $daoName();
270 $fieldSpec = $dao->getFieldSpec($fieldName);
272 // If neither worked then this field doesn't exist. Return false.
273 if (empty($fieldSpec)) {
277 elseif (!empty($fieldSpec['pseudoconstant'])) {
278 $pseudoconstant = $fieldSpec['pseudoconstant'];
280 // if callback is specified..
281 if (!empty($pseudoconstant['callback'])) {
282 return call_user_func(Civi\Core\Resolver
::singleton()->get($pseudoconstant['callback']));
285 // Merge params with schema defaults
287 'condition' => CRM_Utils_Array
::value('condition', $pseudoconstant, array()),
288 'keyColumn' => CRM_Utils_Array
::value('keyColumn', $pseudoconstant),
289 'labelColumn' => CRM_Utils_Array
::value('labelColumn', $pseudoconstant),
292 if ($context == 'abbreviate') {
293 switch ($fieldName) {
294 case 'state_province_id':
295 $params['labelColumn'] = 'abbreviation';
299 $params['labelColumn'] = 'iso_code';
306 // Fetch option group from option_value table
307 if (!empty($pseudoconstant['optionGroupName'])) {
308 if ($context == 'validate') {
309 $params['labelColumn'] = 'name';
311 if ($context == 'match') {
312 $params['keyColumn'] = 'name';
314 // Call our generic fn for retrieving from the option_value table
315 return CRM_Core_OptionGroup
::values(
316 $pseudoconstant['optionGroupName'],
320 $params['condition'] ?
' AND ' . implode(' AND ', (array) $params['condition']) : NULL,
321 $params['labelColumn'] ?
$params['labelColumn'] : 'label',
322 $params['onlyActive'],
324 $params['keyColumn'] ?
$params['keyColumn'] : 'value'
328 // Fetch options from other tables
329 if (!empty($pseudoconstant['table'])) {
330 // Normalize params so the serialized cache string will be consistent.
331 CRM_Utils_Array
::remove($params, 'flip', 'fresh');
333 $cacheKey = $daoName . $fieldName . serialize($params);
335 // Retrieve cached options
336 if (isset(self
::$cache[$cacheKey]) && empty($params['fresh'])) {
337 $output = self
::$cache[$cacheKey];
340 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($pseudoconstant['table']);
341 if (!class_exists($daoName)) {
344 // Get list of fields for the option table
345 $dao = new $daoName();
346 $availableFields = array_keys($dao->fieldKeys());
349 $select = "SELECT %1 AS id, %2 AS label";
352 $order = "ORDER BY %2";
354 // Use machine name in certain contexts
355 if ($context == 'validate' ||
$context == 'match') {
356 $nameField = $context == 'validate' ?
'labelColumn' : 'keyColumn';
357 if (!empty($pseudoconstant['nameColumn'])) {
358 $params[$nameField] = $pseudoconstant['nameColumn'];
360 elseif (in_array('name', $availableFields)) {
361 $params[$nameField] = 'name';
364 // Condition param can be passed as an sql clause string or an array of clauses
365 if (!empty($params['condition'])) {
366 $wheres[] = implode(' AND ', (array) $params['condition']);
368 // onlyActive param will automatically filter on common flags
369 if (!empty($params['onlyActive'])) {
370 foreach (array('is_active' => 1, 'is_deleted' => 0, 'is_test' => 0, 'is_hidden' => 0) as $flag => $val) {
371 if (in_array($flag, $availableFields)) {
372 $wheres[] = "$flag = $val";
376 // Filter domain specific options
377 if (in_array('domain_id', $availableFields)) {
378 $wheres[] = 'domain_id = ' . CRM_Core_Config
::domainID();
380 $queryParams = array(
381 1 => array($params['keyColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
382 2 => array($params['labelColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
383 3 => array($pseudoconstant['table'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
385 // Add orderColumn param
386 if (!empty($params['orderColumn'])) {
387 $queryParams[4] = array($params['orderColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
);
388 $order = "ORDER BY %4";
390 // Support no sorting if $params[orderColumn] is FALSE
391 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
394 // Default to 'weight' if that column exists
395 elseif (in_array('weight', $availableFields)) {
396 $order = "ORDER BY weight";
400 $query = "$select $from";
402 $query .= " WHERE " . implode($wheres, ' AND ');
404 $query .= ' ' . $order;
405 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
406 while ($dao->fetch()) {
407 $output[$dao->id
] = $dao->label
;
411 if (!empty($params['localize']) ||
$pseudoconstant['table'] == 'civicrm_country' ||
$pseudoconstant['table'] == 'civicrm_state_province') {
412 $I18nParams = array();
413 if ($pseudoconstant['table'] == 'civicrm_country') {
414 $I18nParams['context'] = 'country';
416 if ($pseudoconstant['table'] == 'civicrm_state_province') {
417 $I18nParams['context'] = 'province';
419 $i18n = CRM_Core_I18n
::singleton();
420 $i18n->localizeArray($output, $I18nParams);
421 // Maintain sort by label
422 if ($order == "ORDER BY %2") {
423 CRM_Utils_Array
::asort($output);
426 self
::$cache[$cacheKey] = $output;
428 return $flip ?
array_flip($output) : $output;
432 // Return "Yes" and "No" for boolean fields
433 elseif (CRM_Utils_Array
::value('type', $fieldSpec) === CRM_Utils_Type
::T_BOOLEAN
) {
434 $output = $context == 'validate' ?
array(0, 1) : array(1 => ts('Yes'), 0 => ts('No'));
435 return $flip ?
array_flip($output) : $output;
437 // If we're still here, it's an error. Return FALSE.
442 * Fetch the translated label for a field given its key.
444 * @param string $baoName
445 * @param string $fieldName
446 * @param string|Int $key
448 * TODO: Accept multivalued input?
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 getLabel($baoName, $fieldName, $key) {
456 $values = $baoName::buildOptions($fieldName, 'get');
457 if ($values === FALSE) {
460 return CRM_Utils_Array
::value($key, $values);
464 * Fetch the machine name for a field given its key.
466 * @param string $baoName
467 * @param string $fieldName
468 * @param string|Int $key
470 * @return bool|null|string
471 * FALSE if the given field has no associated option list
472 * NULL if the given key has no corresponding option
473 * String if label is found
475 public static function getName($baoName, $fieldName, $key) {
476 $values = $baoName::buildOptions($fieldName, 'validate');
477 if ($values === FALSE) {
480 return CRM_Utils_Array
::value($key, $values);
484 * Fetch the key for a field option given its name.
486 * @param string $baoName
487 * @param string $fieldName
488 * @param string|Int $value
490 * @return bool|null|string|int
491 * FALSE if the given field has no associated option list
492 * NULL if the given key has no corresponding option
493 * String|Number if key is found
495 public static function getKey($baoName, $fieldName, $value) {
496 $values = $baoName::buildOptions($fieldName, 'validate');
497 if ($values === FALSE) {
500 return CRM_Utils_Array
::key($value, $values);
504 * Lookup the admin page at which a field's option list can be edited
506 * @return string|null
508 public static function getOptionEditUrl($fieldSpec) {
509 // If it's an option group, that's easy
510 if (!empty($fieldSpec['pseudoconstant']['optionGroupName'])) {
511 return 'civicrm/admin/options/' . $fieldSpec['pseudoconstant']['optionGroupName'];
513 // For everything else...
514 elseif (!empty($fieldSpec['pseudoconstant']['table'])) {
515 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($fieldSpec['pseudoconstant']['table']);
519 // We don't have good mapping so have to do a bit of guesswork from the menu
520 list(, $parent, , $child) = explode('_', $daoName);
521 $sql = "SELECT path FROM civicrm_menu
522 WHERE page_callback LIKE '%CRM_Admin_Page_$child%' OR page_callback LIKE '%CRM_{$parent}_Page_$child%'
523 ORDER BY page_callback
525 return CRM_Core_Dao
::singleValueQuery($sql);
531 * DEPRECATED generic populate method.
532 * All pseudoconstant functions that use this method are also @deprecated
534 * The static array $var is populated from the db
535 * using the <b>$name DAO</b>.
537 * Note: any database errors will be trapped by the DAO.
540 * The associative array we will fill.
541 * @param string $name
542 * The name of the DAO.
544 * Get all objects. default is to get only active ones.
545 * @param string $retrieve
546 * The field that we are interested in (normally name, differs in some objects).
547 * @param string $filter
548 * The field that we want to filter the result set with.
549 * @param string $condition
550 * The condition that gets passed to the final query as the WHERE clause.
552 * @param null $orderby
558 public static function populate(
563 $filter = 'is_active',
569 $cacheKey = "CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}";
570 $cache = CRM_Utils_Cache
::singleton();
571 $var = $cache->get($cacheKey);
572 if ($var && empty($force)) {
576 $object = new $name();
578 $object->selectAdd();
579 $object->selectAdd("$key, $retrieve");
581 $object->whereAdd($condition);
585 $object->orderBy($retrieve);
588 $object->orderBy($orderby);
592 $object->$filter = 1;
597 while ($object->fetch()) {
598 $var[$object->$key] = $object->$retrieve;
601 $cache->set($cacheKey, $var);
605 * Flush given pseudoconstant so it can be reread from db.
606 * nex time it's requested.
609 * @param bool|string $name pseudoconstant to be flushed
611 public static function flush($name = 'cache') {
612 if (isset(self
::$
$name)) {
615 if ($name == 'cache') {
616 CRM_Core_OptionGroup
::flushAll();
621 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
623 * Get all Activty types.
625 * The static array activityType is returned
629 * array reference of all activity types.
631 public static function &activityType() {
632 $args = func_get_args();
633 $all = CRM_Utils_Array
::value(0, $args, TRUE);
634 $includeCaseActivities = CRM_Utils_Array
::value(1, $args, FALSE);
635 $reset = CRM_Utils_Array
::value(2, $args, FALSE);
636 $returnColumn = CRM_Utils_Array
::value(3, $args, 'label');
637 $includeCampaignActivities = CRM_Utils_Array
::value(4, $args, FALSE);
638 $onlyComponentActivities = CRM_Utils_Array
::value(5, $args, FALSE);
639 $index = (int) $all . '_' . $returnColumn . '_' . (int) $includeCaseActivities;
640 $index .= '_' . (int) $includeCampaignActivities;
641 $index .= '_' . (int) $onlyComponentActivities;
643 if (NULL === self
::$activityType) {
644 self
::$activityType = array();
647 if (!isset(self
::$activityType[$index]) ||
$reset) {
650 $condition = 'AND filter = 0';
652 $componentClause = " v.component_id IS NULL";
653 if ($onlyComponentActivities) {
654 $componentClause = " v.component_id IS NOT NULL";
657 $componentIds = array();
658 $compInfo = CRM_Core_Component
::getEnabledComponents();
660 // build filter for listing activity types only if their
661 // respective components are enabled
662 foreach ($compInfo as $compName => $compObj) {
663 if ($compName == 'CiviCase') {
664 if ($includeCaseActivities) {
665 $componentIds[] = $compObj->componentID
;
668 elseif ($compName == 'CiviCampaign') {
669 if ($includeCampaignActivities) {
670 $componentIds[] = $compObj->componentID
;
674 $componentIds[] = $compObj->componentID
;
678 if (count($componentIds)) {
679 $componentIds = implode(',', $componentIds);
680 $componentClause = " ($componentClause OR v.component_id IN ($componentIds))";
681 if ($onlyComponentActivities) {
682 $componentClause = " ( v.component_id IN ($componentIds ) )";
685 $condition = $condition . ' AND ' . $componentClause;
687 self
::$activityType[$index] = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
689 return self
::$activityType[$index];
693 * Get all the State/Province from database.
695 * The static array stateProvince is returned, and if it's
696 * called the first time, the <b>State Province DAO</b> is used
697 * to get all the States.
699 * Note: any database errors will be trapped by the DAO.
702 * @param bool|int $id - Optional id to return
707 * array reference of all State/Provinces.
709 public static function &stateProvince($id = FALSE, $limit = TRUE) {
710 if (($id && !CRM_Utils_Array
::value($id, self
::$stateProvince)) ||
!self
::$stateProvince ||
!$id) {
711 $whereClause = FALSE;
712 $config = CRM_Core_Config
::singleton();
714 $countryIsoCodes = self
::countryIsoCode();
715 $limitCodes = $config->provinceLimit();
717 foreach ($limitCodes as $code) {
718 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
720 if (!empty($limitIds)) {
721 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
724 $whereClause = FALSE;
727 self
::populate(self
::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
729 // localise the province names if in an non-en_US locale
731 if ($tsLocale != '' and $tsLocale != 'en_US') {
732 $i18n = CRM_Core_I18n
::singleton();
733 $i18n->localizeArray(self
::$stateProvince, array(
734 'context' => 'province',
736 self
::$stateProvince = CRM_Utils_Array
::asort(self
::$stateProvince);
740 if (array_key_exists($id, self
::$stateProvince)) {
741 return self
::$stateProvince[$id];
748 return self
::$stateProvince;
752 * Get all the State/Province abbreviations from the database.
754 * Same as above, except gets the abbreviations instead of the names.
757 * @param bool|int $id - Optional id to return
762 * array reference of all State/Province abbreviations.
764 public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
768 FROM civicrm_state_province
776 return CRM_Core_DAO
::singleValueQuery($query, $params);
779 if (!self
::$stateProvinceAbbreviation ||
!$id) {
781 $whereClause = FALSE;
784 $config = CRM_Core_Config
::singleton();
785 $countryIsoCodes = self
::countryIsoCode();
786 $limitCodes = $config->provinceLimit();
788 foreach ($limitCodes as $code) {
789 $tmpArray = array_keys($countryIsoCodes, $code);
791 if (!empty($tmpArray)) {
792 $limitIds[] = array_shift($tmpArray);
795 if (!empty($limitIds)) {
796 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
799 self
::populate(self
::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
803 if (array_key_exists($id, self
::$stateProvinceAbbreviation)) {
804 return self
::$stateProvinceAbbreviation[$id];
811 return self
::$stateProvinceAbbreviation;
815 * Get all the countries from database.
817 * The static array country is returned, and if it's
818 * called the first time, the <b>Country DAO</b> is used
819 * to get all the countries.
821 * Note: any database errors will be trapped by the DAO.
824 * @param bool|int $id - Optional id to return
826 * @param bool $applyLimit
829 * array reference of all countries.
831 public static function country($id = FALSE, $applyLimit = TRUE) {
832 if (($id && !CRM_Utils_Array
::value($id, self
::$country)) ||
!self
::$country ||
!$id) {
834 $config = CRM_Core_Config
::singleton();
835 $limitCodes = array();
838 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
839 // (ensuring it's a subset of the legal values)
840 // K/P: We need to fix this, i dont think it works with new setting files
841 $limitCodes = $config->countryLimit();
842 if (!is_array($limitCodes)) {
844 $config->countryLimit
=> 1,
848 $limitCodes = array_intersect(self
::countryIsoCode(), $limitCodes);
851 if (count($limitCodes)) {
852 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
858 self
::populate(self
::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
860 // if default country is set, percolate it to the top
861 if ($config->defaultContactCountry()) {
862 $countryIsoCodes = self
::countryIsoCode();
863 $defaultID = array_search($config->defaultContactCountry(), $countryIsoCodes);
864 if ($defaultID !== FALSE) {
865 $default[$defaultID] = CRM_Utils_Array
::value($defaultID, self
::$country);
866 self
::$country = $default + self
::$country;
870 // localise the country names if in an non-en_US locale
872 if ($tsLocale != '' and $tsLocale != 'en_US') {
873 $i18n = CRM_Core_I18n
::singleton();
874 $i18n->localizeArray(self
::$country, array(
875 'context' => 'country',
877 self
::$country = CRM_Utils_Array
::asort(self
::$country);
881 if (array_key_exists($id, self
::$country)) {
882 return self
::$country[$id];
885 return CRM_Core_DAO
::$_nullObject;
888 return self
::$country;
892 * Get all the country ISO Code abbreviations from the database.
894 * The static array countryIsoCode is returned, and if it's
895 * called the first time, the <b>Country DAO</b> is used
896 * to get all the countries' ISO codes.
898 * Note: any database errors will be trapped by the DAO.
904 * array reference of all country ISO codes.
906 public static function &countryIsoCode($id = FALSE) {
907 if (!self
::$countryIsoCode) {
908 self
::populate(self
::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
911 if (array_key_exists($id, self
::$countryIsoCode)) {
912 return self
::$countryIsoCode[$id];
915 return CRM_Core_DAO
::$_nullObject;
918 return self
::$countryIsoCode;
922 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
924 * Get all groups from database
926 * The static array group is returned, and if it's
927 * called the first time, the <b>Group DAO</b> is used
928 * to get all the groups.
930 * Note: any database errors will be trapped by the DAO.
932 * @param string $groupType
933 * Type of group(Access/Mailing).
934 * @param bool $excludeHidden
935 * Exclude hidden groups.
939 * array reference of all groups.
941 public static function &allGroup($groupType = NULL, $excludeHidden = TRUE) {
942 $condition = CRM_Contact_BAO_Group
::groupTypeCondition($groupType, $excludeHidden);
945 self
::$group = array();
948 $groupKey = $groupType ?
$groupType : 'null';
950 if (!isset(self
::$group[$groupKey])) {
951 self
::$group[$groupKey] = NULL;
952 self
::populate(self
::$group[$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
954 return self
::$group[$groupKey];
958 * Create or get groups iterator (iterates over nested groups in a
961 * The GroupNesting instance is returned; it's created if this is being
962 * called for the first time
966 * @param bool $styledLabels
968 * @return CRM_Contact_BAO_GroupNesting
970 public static function &groupIterator($styledLabels = FALSE) {
971 if (!self
::$groupIterator) {
972 // When used as an object, GroupNesting implements Iterator
973 // and iterates nested groups in a logical manner for us
974 self
::$groupIterator = new CRM_Contact_BAO_GroupNesting($styledLabels);
976 return self
::$groupIterator;
980 * Get all permissioned groups from database.
982 * The static array group is returned, and if it's
983 * called the first time, the <b>Group DAO</b> is used
984 * to get all the groups.
986 * Note: any database errors will be trapped by the DAO.
988 * @param string $groupType
989 * Type of group(Access/Mailing).
990 * @param bool $excludeHidden
991 * Exclude hidden groups.
995 * array reference of all groups.
997 public static function group($groupType = NULL, $excludeHidden = TRUE) {
998 return CRM_Core_Permission
::group($groupType, $excludeHidden);
1002 * Fetch groups in a nested format suitable for use in select form element.
1003 * @param bool $checkPermissions
1004 * @param string|null $groupType
1005 * @param bool $excludeHidden
1008 public static function nestedGroup($checkPermissions = TRUE, $groupType = NULL, $excludeHidden = TRUE) {
1009 $groups = $checkPermissions ? self
::group($groupType, $excludeHidden) : self
::allGroup($groupType, $excludeHidden);
1010 return CRM_Contact_BAO_Group
::getGroupsHierarchy($groups, NULL, ' ', TRUE);
1014 * Get all permissioned groups from database.
1016 * The static array group is returned, and if it's
1017 * called the first time, the <b>Group DAO</b> is used
1018 * to get all the groups.
1020 * Note: any database errors will be trapped by the DAO.
1023 * @param bool $onlyPublic
1024 * @param null $groupType
1025 * @param bool $excludeHidden
1028 * array reference of all groups.
1030 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
1031 if (!self
::$staticGroup) {
1032 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
1034 $condition .= " AND visibility != 'User and User Admin Only'";
1038 $condition .= ' AND ' . CRM_Contact_BAO_Group
::groupTypeCondition($groupType);
1041 if ($excludeHidden) {
1042 $condition .= ' AND is_hidden != 1 ';
1045 self
::populate(self
::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
1048 return self
::$staticGroup;
1052 * Get all Relationship Types from database.
1054 * The static array group is returned, and if it's
1055 * called the first time, the <b>RelationshipType DAO</b> is used
1056 * to get all the relationship types.
1058 * Note: any database errors will be trapped by the DAO.
1060 * @param string $valueColumnName
1061 * Db column name/label.
1062 * @param bool $reset
1063 * Reset relationship types if true.
1067 * array reference of all relationship types.
1069 public static function &relationshipType($valueColumnName = 'label', $reset = FALSE) {
1070 if (!CRM_Utils_Array
::value($valueColumnName, self
::$relationshipType) ||
$reset) {
1071 self
::$relationshipType[$valueColumnName] = array();
1073 //now we have name/label columns CRM-3336
1074 $column_a_b = "{$valueColumnName}_a_b";
1075 $column_b_a = "{$valueColumnName}_b_a";
1077 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1078 $relationshipTypeDAO->selectAdd();
1079 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1080 $relationshipTypeDAO->is_active
= 1;
1081 $relationshipTypeDAO->find();
1082 while ($relationshipTypeDAO->fetch()) {
1084 self
::$relationshipType[$valueColumnName][$relationshipTypeDAO->id
] = array(
1085 'id' => $relationshipTypeDAO->id
,
1086 $column_a_b => $relationshipTypeDAO->$column_a_b,
1087 $column_b_a => $relationshipTypeDAO->$column_b_a,
1088 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1089 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1090 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1091 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1096 return self
::$relationshipType[$valueColumnName];
1100 * Get all the ISO 4217 currency codes
1102 * so far, we use this for validation only, so there's no point of putting this into the database
1106 * array reference of all currency codes
1108 public static function ¤cyCode() {
1109 if (!self
::$currencyCode) {
1110 self
::$currencyCode = array(
1380 return self
::$currencyCode;
1384 * Get all the County from database.
1386 * The static array county is returned, and if it's
1387 * called the first time, the <b>County DAO</b> is used
1388 * to get all the Counties.
1390 * Note: any database errors will be trapped by the DAO.
1393 * @param bool|int $id - Optional id to return
1396 * array reference of all Counties
1398 public static function &county($id = FALSE) {
1399 if (!self
::$county) {
1401 $config = CRM_Core_Config
::singleton();
1402 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1403 self
::populate(self
::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1406 if (array_key_exists($id, self
::$county)) {
1407 return self
::$county[$id];
1410 return CRM_Core_DAO
::$_nullObject;
1413 return self
::$county;
1417 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1418 * Get all active payment processors
1420 * The static array paymentProcessor is returned
1424 * Get payment processors - default is to get only active ones.
1426 * Get test payment processors.
1428 * @param null $additionalCond
1431 * array of all payment processors
1433 public static function paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1434 $condition = "is_test = ";
1435 $condition .= ($test) ?
'1' : '0';
1437 if ($additionalCond) {
1438 $condition .= " AND ( $additionalCond ) ";
1441 // CRM-7178. Make sure we only include payment processors valid in this
1443 $condition .= " AND domain_id = " . CRM_Core_Config
::domainID();
1445 $cacheKey = $condition . '_' . (int) $all;
1446 if (!isset(self
::$paymentProcessor[$cacheKey])) {
1447 self
::populate(self
::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1450 return self
::$paymentProcessor[$cacheKey];
1454 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1456 * The static array paymentProcessorType is returned
1460 * Get payment processors - default is to get only active ones.
1463 * @param string $return
1466 * array of all payment processor types
1468 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1469 $cacheKey = $id . '_' . $return;
1470 if (empty(self
::$paymentProcessorType[$cacheKey])) {
1471 self
::populate(self
::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1473 if ($id && CRM_Utils_Array
::value($id, self
::$paymentProcessorType[$cacheKey])) {
1474 return self
::$paymentProcessorType[$cacheKey][$id];
1476 return self
::$paymentProcessorType[$cacheKey];
1480 * Get all the World Regions from Database.
1486 * array reference of all World Regions
1488 public static function &worldRegion($id = FALSE) {
1489 if (!self
::$worldRegions) {
1490 self
::populate(self
::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1494 if (array_key_exists($id, self
::$worldRegions)) {
1495 return self
::$worldRegions[$id];
1498 return CRM_Core_DAO
::$_nullObject;
1502 return self
::$worldRegions;
1506 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1508 * Get all Activity Statuses.
1510 * The static array activityStatus is returned
1513 * @param string $column
1516 * array reference of all activity statuses
1518 public static function &activityStatus($column = 'label') {
1519 if (NULL === self
::$activityStatus) {
1520 self
::$activityStatus = array();
1522 if (!array_key_exists($column, self
::$activityStatus)) {
1523 self
::$activityStatus[$column] = array();
1525 self
::$activityStatus[$column] = CRM_Core_OptionGroup
::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1528 return self
::$activityStatus[$column];
1532 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1534 * Get all Visibility levels.
1536 * The static array visibility is returned
1539 * @param string $column
1542 * array reference of all Visibility levels.
1544 public static function &visibility($column = 'label') {
1545 if (!isset(self
::$visibility)) {
1546 self
::$visibility = array();
1549 if (!isset(self
::$visibility[$column])) {
1550 self
::$visibility[$column] = CRM_Core_OptionGroup
::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1553 return self
::$visibility[$column];
1557 * @param int $countryID
1558 * @param string $field
1562 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1563 static $_cache = NULL;
1565 $cacheKey = "{$countryID}_{$field}";
1570 if (!empty($_cache[$cacheKey])) {
1571 return $_cache[$cacheKey];
1575 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1576 FROM civicrm_state_province
1577 WHERE country_id = %1
1586 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1589 while ($dao->fetch()) {
1590 $result[$dao->id
] = $dao->name
;
1593 // localise the stateProvince names if in an non-en_US locale
1594 $config = CRM_Core_Config
::singleton();
1596 if ($tsLocale != '' and $tsLocale != 'en_US') {
1597 $i18n = CRM_Core_I18n
::singleton();
1598 $i18n->localizeArray($result, array(
1599 'context' => 'province',
1601 $result = CRM_Utils_Array
::asort($result);
1604 $_cache[$cacheKey] = $result;
1606 CRM_Utils_Hook
::buildStateProvinceForCountry($countryID, $result);
1612 * @param int $stateID
1616 public static function &countyForState($stateID) {
1617 if (is_array($stateID)) {
1618 $states = implode(", ", $stateID);
1620 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1622 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1623 WHERE civicrm_county.state_province_id in ( $states )
1624 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1626 $dao = CRM_Core_DAO
::executeQuery($query);
1629 while ($dao->fetch()) {
1630 $result[$dao->id
] = $dao->abbreviation
. ': ' . $dao->name
;
1635 static $_cache = NULL;
1637 $cacheKey = "{$stateID}_name";
1642 if (!empty($_cache[$cacheKey])) {
1643 return $_cache[$cacheKey];
1647 SELECT civicrm_county.name name, civicrm_county.id id
1649 WHERE state_province_id = %1
1658 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1661 while ($dao->fetch()) {
1662 $result[$dao->id
] = $dao->name
;
1670 * Given a state ID return the country ID, this allows
1671 * us to populate forms and values for downstream code
1673 * @param int $stateID
1676 * the country id that the state belongs to
1678 public static function countryIDForStateID($stateID) {
1679 if (empty($stateID)) {
1680 return CRM_Core_DAO
::$_nullObject;
1685 FROM civicrm_state_province
1688 $params = array(1 => array($stateID, 'Integer'));
1690 return CRM_Core_DAO
::singleValueQuery($query, $params);
1694 * Get all types of Greetings.
1696 * The static array of greeting is returned
1700 * Get All Email Greetings - default is to get only active ones.
1702 * @param string $columnName
1705 * array reference of all greetings.
1707 public static function greeting($filter, $columnName = 'label') {
1708 $index = $filter['greeting_type'] . '_' . $columnName;
1710 // also add contactType to the array
1711 $contactType = CRM_Utils_Array
::value('contact_type', $filter);
1713 $index .= '_' . $contactType;
1716 if (NULL === self
::$greeting) {
1717 self
::$greeting = array();
1720 if (!CRM_Utils_Array
::value($index, self
::$greeting)) {
1721 $filterCondition = NULL;
1723 $filterVal = 'v.filter =';
1724 switch ($contactType) {
1733 case 'Organization':
1737 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1740 self
::$greeting[$index] = CRM_Core_OptionGroup
::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1743 return self
::$greeting[$index];
1747 * Construct array of default greeting values for contact type.
1751 * array reference of default greetings.
1753 public static function &greetingDefaults() {
1754 if (!self
::$greetingDefaults) {
1755 $defaultGreetings = array();
1756 $contactTypes = self
::get('CRM_Contact_DAO_Contact', 'contact_type', array(
1757 'keyColumn' => 'id',
1758 'labelColumn' => 'name',
1761 foreach ($contactTypes as $filter => $contactType) {
1762 $filterCondition = " AND (v.filter = 0 OR v.filter = $filter) AND v.is_default = 1 ";
1764 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1765 $tokenVal = CRM_Core_OptionGroup
::values($greeting, NULL, NULL, NULL, $filterCondition, 'label');
1766 $defaultGreetings[$contactType][$greeting] = $tokenVal;
1770 self
::$greetingDefaults = $defaultGreetings;
1773 return self
::$greetingDefaults;
1777 * Get all extensions.
1779 * The static array extensions
1781 * FIXME: This is called by civix but not by any core code. We
1782 * should provide an API call which civix can use instead.
1786 * array($fullyQualifiedName => $label) list of extensions
1788 public static function &getExtensions() {
1789 if (!self
::$extensions) {
1790 self
::$extensions = array();
1792 SELECT full_name, label
1793 FROM civicrm_extension
1796 $dao = CRM_Core_DAO
::executeQuery($sql);
1797 while ($dao->fetch()) {
1798 self
::$extensions[$dao->full_name
] = $dao->label
;
1802 return self
::$extensions;
1806 * Get all options values.
1808 * The static array option values is returned
1811 * @param bool $optionGroupName
1812 * Get All Option Group values- default is to get only active ones.
1815 * @param null $condition
1818 * array reference of all Option Group Name
1820 public static function accountOptionValues($optionGroupName, $id = NULL, $condition = NULL) {
1821 $cacheKey = $optionGroupName . '_' . $condition;
1822 if (empty(self
::$accountOptionValues[$cacheKey])) {
1823 self
::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup
::values($optionGroupName, FALSE, FALSE, FALSE, $condition);
1826 return CRM_Utils_Array
::value($id, self
::$accountOptionValues[$cacheKey]);
1829 return self
::$accountOptionValues[$cacheKey];
1833 * Fetch the list of active extensions of type 'module'
1835 * @param bool $fresh
1836 * Whether to forcibly reload extensions list from canonical store.
1839 * array(array('prefix' => $, 'file' => $))
1841 public static function getModuleExtensions($fresh = FALSE) {
1842 return CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles($fresh);
1847 * Get all tax rates.
1849 * The static array tax rates is returned
1852 * array list of tax rates with the financial type
1854 public static function getTaxRates() {
1855 if (!self
::$taxRates) {
1856 self
::$taxRates = array();
1858 SELECT fa.tax_rate, efa.entity_id
1859 FROM civicrm_entity_financial_account efa
1860 INNER JOIN civicrm_financial_account fa ON fa.id = efa.financial_account_id
1861 INNER JOIN civicrm_option_value cov ON cov.value = efa.account_relationship
1862 INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id
1863 WHERE efa.entity_table = 'civicrm_financial_type'
1864 AND cov.name = 'Sales Tax Account is'
1865 AND cog.name = 'account_relationship'
1866 AND fa.is_active = 1";
1867 $dao = CRM_Core_DAO
::executeQuery($sql);
1868 while ($dao->fetch()) {
1869 self
::$taxRates[$dao->entity_id
] = $dao->tax_rate
;
1873 return self
::$taxRates;