3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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 * @param string $daoName
196 * @param string $fieldName
197 * @param array $params
198 * - name string name of the option group
199 * - flip boolean results are return in id => label format if false
200 * if true, the results are reversed
201 * - grouping boolean if true, return the value in 'grouping' column (currently unsupported for tables other than option_value)
202 * - localize boolean if true, localize the results before returning
203 * - condition string|array add condition(s) to the sql query - will be concatenated using 'AND'
204 * - keyColumn string the column to use for 'id'
205 * - labelColumn string the column to use for 'label'
206 * - orderColumn string the column to use for sorting, defaults to 'weight' column if one exists, else defaults to labelColumn
207 * - onlyActive boolean return only the action option values
208 * - fresh boolean ignore cache entries and go back to DB
209 * @param string $context : Context string
212 * array on success, FALSE on error.
215 public static function get($daoName, $fieldName, $params = array(), $context = NULL) {
216 CRM_Core_DAO
::buildOptionsContext($context);
217 $flip = !empty($params['flip']);
218 // Merge params with defaults
222 'onlyActive' => ($context == 'validate' ||
$context == 'get') ?
FALSE : TRUE,
226 // Custom fields are not in the schema
227 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
228 $customField = new CRM_Core_DAO_CustomField();
229 $customField->id
= (int) substr($fieldName, 7);
230 $customField->find(TRUE);
233 if (!empty($customField->option_group_id
)) {
234 $options = CRM_Core_OptionGroup
::valuesByID($customField->option_group_id
,
238 // Note: for custom fields the 'name' column is NULL
239 CRM_Utils_Array
::value('labelColumn', $params, 'label'),
240 $params['onlyActive'],
245 if ($customField->data_type
=== 'StateProvince') {
246 $options = self
::stateProvince();
248 elseif ($customField->data_type
=== 'Country') {
249 $options = $context == 'validate' ? self
::countryIsoCode() : self
::country();
251 elseif ($customField->data_type
=== 'Boolean') {
252 $options = $context == 'validate' ?
array(0, 1) : CRM_Core_SelectValues
::boolean();
255 CRM_Utils_Hook
::customFieldOptions($customField->id
, $options, FALSE);
256 if ($options && $flip) {
257 $options = array_flip($options);
259 $customField->free();
263 // Core field: load schema
264 $dao = new $daoName();
265 $fieldSpec = $dao->getFieldSpec($fieldName);
267 // If neither worked then this field doesn't exist. Return false.
268 if (empty($fieldSpec)) {
272 elseif (!empty($fieldSpec['pseudoconstant'])) {
273 $pseudoconstant = $fieldSpec['pseudoconstant'];
275 // if callback is specified..
276 if (!empty($pseudoconstant['callback'])) {
277 return call_user_func(Civi\Core\Resolver
::singleton()->get($pseudoconstant['callback']));
280 // Merge params with schema defaults
282 'condition' => CRM_Utils_Array
::value('condition', $pseudoconstant, array()),
283 'keyColumn' => CRM_Utils_Array
::value('keyColumn', $pseudoconstant),
284 'labelColumn' => CRM_Utils_Array
::value('labelColumn', $pseudoconstant),
287 if ($context == 'abbreviate') {
288 switch ($fieldName) {
289 case 'state_province_id':
290 $params['labelColumn'] = 'abbreviation';
294 $params['labelColumn'] = 'iso_code';
301 // Fetch option group from option_value table
302 if (!empty($pseudoconstant['optionGroupName'])) {
303 if ($context == 'validate') {
304 $params['labelColumn'] = 'name';
306 if ($context == 'match') {
307 $params['keyColumn'] = 'name';
309 // Call our generic fn for retrieving from the option_value table
310 return CRM_Core_OptionGroup
::values(
311 $pseudoconstant['optionGroupName'],
315 $params['condition'] ?
' AND ' . implode(' AND ', (array) $params['condition']) : NULL,
316 $params['labelColumn'] ?
$params['labelColumn'] : 'label',
317 $params['onlyActive'],
319 $params['keyColumn'] ?
$params['keyColumn'] : 'value'
323 // Fetch options from other tables
324 if (!empty($pseudoconstant['table'])) {
325 // Normalize params so the serialized cache string will be consistent.
326 CRM_Utils_Array
::remove($params, 'flip', 'fresh');
328 $cacheKey = $daoName . $fieldName . serialize($params);
330 // Retrieve cached options
331 if (isset(self
::$cache[$cacheKey]) && empty($params['fresh'])) {
332 $output = self
::$cache[$cacheKey];
335 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($pseudoconstant['table']);
336 if (!class_exists($daoName)) {
339 // Get list of fields for the option table
340 $dao = new $daoName();
341 $availableFields = array_keys($dao->fieldKeys());
344 $select = "SELECT %1 AS id, %2 AS label";
347 $order = "ORDER BY %2";
349 // Use machine name in certain contexts
350 if ($context == 'validate' ||
$context == 'match') {
351 $nameField = $context == 'validate' ?
'labelColumn' : 'keyColumn';
352 if (!empty($pseudoconstant['nameColumn'])) {
353 $params[$nameField] = $pseudoconstant['nameColumn'];
355 elseif (in_array('name', $availableFields)) {
356 $params[$nameField] = 'name';
359 // Condition param can be passed as an sql clause string or an array of clauses
360 if (!empty($params['condition'])) {
361 $wheres[] = implode(' AND ', (array) $params['condition']);
363 // onlyActive param will automatically filter on common flags
364 if (!empty($params['onlyActive'])) {
365 foreach (array('is_active' => 1, 'is_deleted' => 0, 'is_test' => 0, 'is_hidden' => 0) as $flag => $val) {
366 if (in_array($flag, $availableFields)) {
367 $wheres[] = "$flag = $val";
371 // Filter domain specific options
372 if (in_array('domain_id', $availableFields)) {
373 $wheres[] = 'domain_id = ' . CRM_Core_Config
::domainID();
375 $queryParams = array(
376 1 => array($params['keyColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
377 2 => array($params['labelColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
378 3 => array($pseudoconstant['table'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
380 // Add orderColumn param
381 if (!empty($params['orderColumn'])) {
382 $queryParams[4] = array($params['orderColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
);
383 $order = "ORDER BY %4";
385 // Support no sorting if $params[orderColumn] is FALSE
386 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
389 // Default to 'weight' if that column exists
390 elseif (in_array('weight', $availableFields)) {
391 $order = "ORDER BY weight";
395 $query = "$select $from";
397 $query .= " WHERE " . implode($wheres, ' AND ');
399 $query .= ' ' . $order;
400 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
401 while ($dao->fetch()) {
402 $output[$dao->id
] = $dao->label
;
406 if (!empty($params['localize']) ||
$pseudoconstant['table'] == 'civicrm_country' ||
$pseudoconstant['table'] == 'civicrm_state_province') {
407 $I18nParams = array();
408 if ($pseudoconstant['table'] == 'civicrm_country') {
409 $I18nParams['context'] = 'country';
411 if ($pseudoconstant['table'] == 'civicrm_state_province') {
412 $I18nParams['context'] = 'province';
414 $i18n = CRM_Core_I18n
::singleton();
415 $i18n->localizeArray($output, $I18nParams);
416 // Maintain sort by label
417 if ($order == "ORDER BY %2") {
418 CRM_Utils_Array
::asort($output);
421 self
::$cache[$cacheKey] = $output;
423 return $flip ?
array_flip($output) : $output;
427 // Return "Yes" and "No" for boolean fields
428 elseif (CRM_Utils_Array
::value('type', $fieldSpec) === CRM_Utils_Type
::T_BOOLEAN
) {
429 $output = $context == 'validate' ?
array(0, 1) : array(1 => ts('Yes'), 0 => ts('No'));
430 return $flip ?
array_flip($output) : $output;
432 // If we're still here, it's an error. Return FALSE.
437 * Fetch the translated label for a field given its key.
439 * @param string $baoName
440 * @param string $fieldName
441 * @param string|Int $key
443 * TODO: Accept multivalued input?
445 * @return bool|null|string
446 * FALSE if the given field has no associated option list
447 * NULL if the given key has no corresponding option
448 * String if label is found
450 public static function getLabel($baoName, $fieldName, $key) {
451 $values = $baoName::buildOptions($fieldName, 'get');
452 if ($values === FALSE) {
455 return CRM_Utils_Array
::value($key, $values);
459 * Fetch the machine name for a field given its key.
461 * @param string $baoName
462 * @param string $fieldName
463 * @param string|Int $key
465 * @return bool|null|string
466 * FALSE if the given field has no associated option list
467 * NULL if the given key has no corresponding option
468 * String if label is found
470 public static function getName($baoName, $fieldName, $key) {
471 $values = $baoName::buildOptions($fieldName, 'validate');
472 if ($values === FALSE) {
475 return CRM_Utils_Array
::value($key, $values);
479 * Fetch the key for a field option given its name.
481 * @param string $baoName
482 * @param string $fieldName
483 * @param string|Int $value
485 * @return bool|null|string|int
486 * FALSE if the given field has no associated option list
487 * NULL if the given key has no corresponding option
488 * String|Number if key is found
490 public static function getKey($baoName, $fieldName, $value) {
491 $values = $baoName::buildOptions($fieldName, 'validate');
492 if ($values === FALSE) {
495 return CRM_Utils_Array
::key($value, $values);
499 * Lookup the admin page at which a field's option list can be edited
501 * @return string|null
503 public static function getOptionEditUrl($fieldSpec) {
504 // If it's an option group, that's easy
505 if (!empty($fieldSpec['pseudoconstant']['optionGroupName'])) {
506 return 'civicrm/admin/options/' . $fieldSpec['pseudoconstant']['optionGroupName'];
508 // For everything else...
509 elseif (!empty($fieldSpec['pseudoconstant']['table'])) {
510 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($fieldSpec['pseudoconstant']['table']);
514 // We don't have good mapping so have to do a bit of guesswork from the menu
515 list(, $parent, , $child) = explode('_', $daoName);
516 $sql = "SELECT path FROM civicrm_menu
517 WHERE page_callback LIKE '%CRM_Admin_Page_$child%' OR page_callback LIKE '%CRM_{$parent}_Page_$child%'
518 ORDER BY page_callback
520 return CRM_Core_Dao
::singleValueQuery($sql);
526 * DEPRECATED generic populate method.
527 * All pseudoconstant functions that use this method are also @deprecated
529 * The static array $var is populated from the db
530 * using the <b>$name DAO</b>.
532 * Note: any database errors will be trapped by the DAO.
535 * The associative array we will fill.
536 * @param string $name
537 * The name of the DAO.
539 * Get all objects. default is to get only active ones.
540 * @param string $retrieve
541 * The field that we are interested in (normally name, differs in some objects).
542 * @param string $filter
543 * The field that we want to filter the result set with.
544 * @param string $condition
545 * The condition that gets passed to the final query as the WHERE clause.
547 * @param null $orderby
553 public static function populate(
558 $filter = 'is_active',
564 $cacheKey = "CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}";
565 $cache = CRM_Utils_Cache
::singleton();
566 $var = $cache->get($cacheKey);
567 if ($var && empty($force)) {
571 $object = new $name();
573 $object->selectAdd();
574 $object->selectAdd("$key, $retrieve");
576 $object->whereAdd($condition);
580 $object->orderBy($retrieve);
583 $object->orderBy($orderby);
587 $object->$filter = 1;
592 while ($object->fetch()) {
593 $var[$object->$key] = $object->$retrieve;
596 $cache->set($cacheKey, $var);
600 * Flush given pseudoconstant so it can be reread from db.
601 * nex time it's requested.
604 * @param bool|string $name pseudoconstant to be flushed
606 public static function flush($name = 'cache') {
607 if (isset(self
::$
$name)) {
610 if ($name == 'cache') {
611 CRM_Core_OptionGroup
::flushAll();
616 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
618 * Get all Activty types.
620 * The static array activityType is returned
624 * array reference of all activity types.
626 public static function &activityType() {
627 $args = func_get_args();
628 $all = CRM_Utils_Array
::value(0, $args, TRUE);
629 $includeCaseActivities = CRM_Utils_Array
::value(1, $args, FALSE);
630 $reset = CRM_Utils_Array
::value(2, $args, FALSE);
631 $returnColumn = CRM_Utils_Array
::value(3, $args, 'label');
632 $includeCampaignActivities = CRM_Utils_Array
::value(4, $args, FALSE);
633 $onlyComponentActivities = CRM_Utils_Array
::value(5, $args, FALSE);
634 $index = (int) $all . '_' . $returnColumn . '_' . (int) $includeCaseActivities;
635 $index .= '_' . (int) $includeCampaignActivities;
636 $index .= '_' . (int) $onlyComponentActivities;
638 if (NULL === self
::$activityType) {
639 self
::$activityType = array();
642 if (!isset(self
::$activityType[$index]) ||
$reset) {
645 $condition = 'AND filter = 0';
647 $componentClause = " v.component_id IS NULL";
648 if ($onlyComponentActivities) {
649 $componentClause = " v.component_id IS NOT NULL";
652 $componentIds = array();
653 $compInfo = CRM_Core_Component
::getEnabledComponents();
655 // build filter for listing activity types only if their
656 // respective components are enabled
657 foreach ($compInfo as $compName => $compObj) {
658 if ($compName == 'CiviCase') {
659 if ($includeCaseActivities) {
660 $componentIds[] = $compObj->componentID
;
663 elseif ($compName == 'CiviCampaign') {
664 if ($includeCampaignActivities) {
665 $componentIds[] = $compObj->componentID
;
669 $componentIds[] = $compObj->componentID
;
673 if (count($componentIds)) {
674 $componentIds = implode(',', $componentIds);
675 $componentClause = " ($componentClause OR v.component_id IN ($componentIds))";
676 if ($onlyComponentActivities) {
677 $componentClause = " ( v.component_id IN ($componentIds ) )";
680 $condition = $condition . ' AND ' . $componentClause;
682 self
::$activityType[$index] = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
684 return self
::$activityType[$index];
688 * Get all the State/Province from database.
690 * The static array stateProvince is returned, and if it's
691 * called the first time, the <b>State Province DAO</b> is used
692 * to get all the States.
694 * Note: any database errors will be trapped by the DAO.
697 * @param bool|int $id - Optional id to return
702 * array reference of all State/Provinces.
704 public static function &stateProvince($id = FALSE, $limit = TRUE) {
705 if (($id && !CRM_Utils_Array
::value($id, self
::$stateProvince)) ||
!self
::$stateProvince ||
!$id) {
706 $whereClause = FALSE;
707 $config = CRM_Core_Config
::singleton();
709 $countryIsoCodes = self
::countryIsoCode();
710 $limitCodes = $config->provinceLimit();
712 foreach ($limitCodes as $code) {
713 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
715 if (!empty($limitIds)) {
716 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
719 $whereClause = FALSE;
722 self
::populate(self
::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
724 // localise the province names if in an non-en_US locale
726 if ($tsLocale != '' and $tsLocale != 'en_US') {
727 $i18n = CRM_Core_I18n
::singleton();
728 $i18n->localizeArray(self
::$stateProvince, array(
729 'context' => 'province',
731 self
::$stateProvince = CRM_Utils_Array
::asort(self
::$stateProvince);
735 if (array_key_exists($id, self
::$stateProvince)) {
736 return self
::$stateProvince[$id];
743 return self
::$stateProvince;
747 * Get all the State/Province abbreviations from the database.
749 * Same as above, except gets the abbreviations instead of the names.
752 * @param bool|int $id - Optional id to return
757 * array reference of all State/Province abbreviations.
759 public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
763 FROM civicrm_state_province
771 return CRM_Core_DAO
::singleValueQuery($query, $params);
774 if (!self
::$stateProvinceAbbreviation ||
!$id) {
776 $whereClause = FALSE;
779 $config = CRM_Core_Config
::singleton();
780 $countryIsoCodes = self
::countryIsoCode();
781 $limitCodes = $config->provinceLimit();
783 foreach ($limitCodes as $code) {
784 $tmpArray = array_keys($countryIsoCodes, $code);
786 if (!empty($tmpArray)) {
787 $limitIds[] = array_shift($tmpArray);
790 if (!empty($limitIds)) {
791 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
794 self
::populate(self
::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
798 if (array_key_exists($id, self
::$stateProvinceAbbreviation)) {
799 return self
::$stateProvinceAbbreviation[$id];
806 return self
::$stateProvinceAbbreviation;
810 * Get all the countries from database.
812 * The static array country is returned, and if it's
813 * called the first time, the <b>Country DAO</b> is used
814 * to get all the countries.
816 * Note: any database errors will be trapped by the DAO.
819 * @param bool|int $id - Optional id to return
821 * @param bool $applyLimit
824 * array reference of all countries.
826 public static function country($id = FALSE, $applyLimit = TRUE) {
827 if (($id && !CRM_Utils_Array
::value($id, self
::$country)) ||
!self
::$country ||
!$id) {
829 $config = CRM_Core_Config
::singleton();
830 $limitCodes = array();
833 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
834 // (ensuring it's a subset of the legal values)
835 // K/P: We need to fix this, i dont think it works with new setting files
836 $limitCodes = $config->countryLimit();
837 if (!is_array($limitCodes)) {
839 $config->countryLimit
=> 1,
843 $limitCodes = array_intersect(self
::countryIsoCode(), $limitCodes);
846 if (count($limitCodes)) {
847 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
853 self
::populate(self
::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
855 // if default country is set, percolate it to the top
856 if ($config->defaultContactCountry()) {
857 $countryIsoCodes = self
::countryIsoCode();
858 $defaultID = array_search($config->defaultContactCountry(), $countryIsoCodes);
859 if ($defaultID !== FALSE) {
860 $default[$defaultID] = CRM_Utils_Array
::value($defaultID, self
::$country);
861 self
::$country = $default + self
::$country;
865 // localise the country names if in an non-en_US locale
867 if ($tsLocale != '' and $tsLocale != 'en_US') {
868 $i18n = CRM_Core_I18n
::singleton();
869 $i18n->localizeArray(self
::$country, array(
870 'context' => 'country',
872 self
::$country = CRM_Utils_Array
::asort(self
::$country);
876 if (array_key_exists($id, self
::$country)) {
877 return self
::$country[$id];
880 return CRM_Core_DAO
::$_nullObject;
883 return self
::$country;
887 * Get all the country ISO Code abbreviations from the database.
889 * The static array countryIsoCode is returned, and if it's
890 * called the first time, the <b>Country DAO</b> is used
891 * to get all the countries' ISO codes.
893 * Note: any database errors will be trapped by the DAO.
899 * array reference of all country ISO codes.
901 public static function &countryIsoCode($id = FALSE) {
902 if (!self
::$countryIsoCode) {
903 self
::populate(self
::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
906 if (array_key_exists($id, self
::$countryIsoCode)) {
907 return self
::$countryIsoCode[$id];
910 return CRM_Core_DAO
::$_nullObject;
913 return self
::$countryIsoCode;
917 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
919 * Get all groups from database
921 * The static array group is returned, and if it's
922 * called the first time, the <b>Group DAO</b> is used
923 * to get all the groups.
925 * Note: any database errors will be trapped by the DAO.
927 * @param string $groupType
928 * Type of group(Access/Mailing).
929 * @param bool $excludeHidden
930 * Exclude hidden groups.
934 * array reference of all groups.
936 public static function &allGroup($groupType = NULL, $excludeHidden = TRUE) {
937 $condition = CRM_Contact_BAO_Group
::groupTypeCondition($groupType, $excludeHidden);
940 self
::$group = array();
943 $groupKey = $groupType ?
$groupType : 'null';
945 if (!isset(self
::$group[$groupKey])) {
946 self
::$group[$groupKey] = NULL;
947 self
::populate(self
::$group[$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
949 return self
::$group[$groupKey];
953 * Create or get groups iterator (iterates over nested groups in a
956 * The GroupNesting instance is returned; it's created if this is being
957 * called for the first time
961 * @param bool $styledLabels
963 * @return CRM_Contact_BAO_GroupNesting
965 public static function &groupIterator($styledLabels = FALSE) {
966 if (!self
::$groupIterator) {
967 // When used as an object, GroupNesting implements Iterator
968 // and iterates nested groups in a logical manner for us
969 self
::$groupIterator = new CRM_Contact_BAO_GroupNesting($styledLabels);
971 return self
::$groupIterator;
975 * Get all permissioned groups from database.
977 * The static array group is returned, and if it's
978 * called the first time, the <b>Group DAO</b> is used
979 * to get all the groups.
981 * Note: any database errors will be trapped by the DAO.
983 * @param string $groupType
984 * Type of group(Access/Mailing).
985 * @param bool $excludeHidden
986 * Exclude hidden groups.
990 * array reference of all groups.
992 public static function group($groupType = NULL, $excludeHidden = TRUE) {
993 return CRM_Core_Permission
::group($groupType, $excludeHidden);
997 * Fetch groups in a nested format suitable for use in select form element.
998 * @param bool $checkPermissions
999 * @param string|null $groupType
1000 * @param bool $excludeHidden
1003 public static function nestedGroup($checkPermissions = TRUE, $groupType = NULL, $excludeHidden = TRUE) {
1004 $groups = $checkPermissions ? self
::group($groupType, $excludeHidden) : self
::allGroup($groupType, $excludeHidden);
1005 return CRM_Contact_BAO_Group
::getGroupsHierarchy($groups, NULL, ' ', TRUE);
1009 * Get all permissioned groups from database.
1011 * The static array group is returned, and if it's
1012 * called the first time, the <b>Group DAO</b> is used
1013 * to get all the groups.
1015 * Note: any database errors will be trapped by the DAO.
1018 * @param bool $onlyPublic
1019 * @param null $groupType
1020 * @param bool $excludeHidden
1023 * array reference of all groups.
1025 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
1026 if (!self
::$staticGroup) {
1027 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
1029 $condition .= " AND visibility != 'User and User Admin Only'";
1033 $condition .= ' AND ' . CRM_Contact_BAO_Group
::groupTypeCondition($groupType);
1036 if ($excludeHidden) {
1037 $condition .= ' AND is_hidden != 1 ';
1040 self
::populate(self
::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
1043 return self
::$staticGroup;
1047 * Get all Relationship Types from database.
1049 * The static array group is returned, and if it's
1050 * called the first time, the <b>RelationshipType DAO</b> is used
1051 * to get all the relationship types.
1053 * Note: any database errors will be trapped by the DAO.
1055 * @param string $valueColumnName
1056 * Db column name/label.
1057 * @param bool $reset
1058 * Reset relationship types if true.
1062 * array reference of all relationship types.
1064 public static function &relationshipType($valueColumnName = 'label', $reset = FALSE) {
1065 if (!CRM_Utils_Array
::value($valueColumnName, self
::$relationshipType) ||
$reset) {
1066 self
::$relationshipType[$valueColumnName] = array();
1068 //now we have name/label columns CRM-3336
1069 $column_a_b = "{$valueColumnName}_a_b";
1070 $column_b_a = "{$valueColumnName}_b_a";
1072 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1073 $relationshipTypeDAO->selectAdd();
1074 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1075 $relationshipTypeDAO->is_active
= 1;
1076 $relationshipTypeDAO->find();
1077 while ($relationshipTypeDAO->fetch()) {
1079 self
::$relationshipType[$valueColumnName][$relationshipTypeDAO->id
] = array(
1080 'id' => $relationshipTypeDAO->id
,
1081 $column_a_b => $relationshipTypeDAO->$column_a_b,
1082 $column_b_a => $relationshipTypeDAO->$column_b_a,
1083 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1084 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1085 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1086 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1091 return self
::$relationshipType[$valueColumnName];
1095 * Get all the ISO 4217 currency codes
1097 * so far, we use this for validation only, so there's no point of putting this into the database
1101 * array reference of all currency codes
1103 public static function ¤cyCode() {
1104 if (!self
::$currencyCode) {
1105 self
::$currencyCode = array(
1375 return self
::$currencyCode;
1379 * Get all the County from database.
1381 * The static array county is returned, and if it's
1382 * called the first time, the <b>County DAO</b> is used
1383 * to get all the Counties.
1385 * Note: any database errors will be trapped by the DAO.
1388 * @param bool|int $id - Optional id to return
1391 * array reference of all Counties
1393 public static function &county($id = FALSE) {
1394 if (!self
::$county) {
1396 $config = CRM_Core_Config
::singleton();
1397 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1398 self
::populate(self
::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1401 if (array_key_exists($id, self
::$county)) {
1402 return self
::$county[$id];
1405 return CRM_Core_DAO
::$_nullObject;
1408 return self
::$county;
1412 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1413 * Get all active payment processors
1415 * The static array paymentProcessor is returned
1419 * Get payment processors - default is to get only active ones.
1421 * Get test payment processors.
1423 * @param null $additionalCond
1426 * array of all payment processors
1428 public static function paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1429 $condition = "is_test = ";
1430 $condition .= ($test) ?
'1' : '0';
1432 if ($additionalCond) {
1433 $condition .= " AND ( $additionalCond ) ";
1436 // CRM-7178. Make sure we only include payment processors valid in this
1438 $condition .= " AND domain_id = " . CRM_Core_Config
::domainID();
1440 $cacheKey = $condition . '_' . (int) $all;
1441 if (!isset(self
::$paymentProcessor[$cacheKey])) {
1442 self
::populate(self
::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1445 return self
::$paymentProcessor[$cacheKey];
1449 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1451 * The static array paymentProcessorType is returned
1455 * Get payment processors - default is to get only active ones.
1458 * @param string $return
1461 * array of all payment processor types
1463 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1464 $cacheKey = $id . '_' . $return;
1465 if (empty(self
::$paymentProcessorType[$cacheKey])) {
1466 self
::populate(self
::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1468 if ($id && CRM_Utils_Array
::value($id, self
::$paymentProcessorType[$cacheKey])) {
1469 return self
::$paymentProcessorType[$cacheKey][$id];
1471 return self
::$paymentProcessorType[$cacheKey];
1475 * Get all the World Regions from Database.
1481 * array reference of all World Regions
1483 public static function &worldRegion($id = FALSE) {
1484 if (!self
::$worldRegions) {
1485 self
::populate(self
::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1489 if (array_key_exists($id, self
::$worldRegions)) {
1490 return self
::$worldRegions[$id];
1493 return CRM_Core_DAO
::$_nullObject;
1497 return self
::$worldRegions;
1501 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1503 * Get all Activity Statuses.
1505 * The static array activityStatus is returned
1508 * @param string $column
1511 * array reference of all activity statuses
1513 public static function &activityStatus($column = 'label') {
1514 if (NULL === self
::$activityStatus) {
1515 self
::$activityStatus = array();
1517 if (!array_key_exists($column, self
::$activityStatus)) {
1518 self
::$activityStatus[$column] = array();
1520 self
::$activityStatus[$column] = CRM_Core_OptionGroup
::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1523 return self
::$activityStatus[$column];
1527 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1529 * Get all Visibility levels.
1531 * The static array visibility is returned
1534 * @param string $column
1537 * array reference of all Visibility levels.
1539 public static function &visibility($column = 'label') {
1540 if (!isset(self
::$visibility)) {
1541 self
::$visibility = array();
1544 if (!isset(self
::$visibility[$column])) {
1545 self
::$visibility[$column] = CRM_Core_OptionGroup
::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1548 return self
::$visibility[$column];
1552 * @param int $countryID
1553 * @param string $field
1557 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1558 static $_cache = NULL;
1560 $cacheKey = "{$countryID}_{$field}";
1565 if (!empty($_cache[$cacheKey])) {
1566 return $_cache[$cacheKey];
1570 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1571 FROM civicrm_state_province
1572 WHERE country_id = %1
1581 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1584 while ($dao->fetch()) {
1585 $result[$dao->id
] = $dao->name
;
1588 // localise the stateProvince names if in an non-en_US locale
1589 $config = CRM_Core_Config
::singleton();
1591 if ($tsLocale != '' and $tsLocale != 'en_US') {
1592 $i18n = CRM_Core_I18n
::singleton();
1593 $i18n->localizeArray($result, array(
1594 'context' => 'province',
1596 $result = CRM_Utils_Array
::asort($result);
1599 $_cache[$cacheKey] = $result;
1601 CRM_Utils_Hook
::buildStateProvinceForCountry($countryID, $result);
1607 * @param int $stateID
1611 public static function &countyForState($stateID) {
1612 if (is_array($stateID)) {
1613 $states = implode(", ", $stateID);
1615 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1617 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1618 WHERE civicrm_county.state_province_id in ( $states )
1619 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1621 $dao = CRM_Core_DAO
::executeQuery($query);
1624 while ($dao->fetch()) {
1625 $result[$dao->id
] = $dao->abbreviation
. ': ' . $dao->name
;
1630 static $_cache = NULL;
1632 $cacheKey = "{$stateID}_name";
1637 if (!empty($_cache[$cacheKey])) {
1638 return $_cache[$cacheKey];
1642 SELECT civicrm_county.name name, civicrm_county.id id
1644 WHERE state_province_id = %1
1653 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1656 while ($dao->fetch()) {
1657 $result[$dao->id
] = $dao->name
;
1665 * Given a state ID return the country ID, this allows
1666 * us to populate forms and values for downstream code
1668 * @param int $stateID
1671 * the country id that the state belongs to
1673 public static function countryIDForStateID($stateID) {
1674 if (empty($stateID)) {
1675 return CRM_Core_DAO
::$_nullObject;
1680 FROM civicrm_state_province
1683 $params = array(1 => array($stateID, 'Integer'));
1685 return CRM_Core_DAO
::singleValueQuery($query, $params);
1689 * Get all types of Greetings.
1691 * The static array of greeting is returned
1695 * Get All Email Greetings - default is to get only active ones.
1697 * @param string $columnName
1700 * array reference of all greetings.
1702 public static function greeting($filter, $columnName = 'label') {
1703 $index = $filter['greeting_type'] . '_' . $columnName;
1705 // also add contactType to the array
1706 $contactType = CRM_Utils_Array
::value('contact_type', $filter);
1708 $index .= '_' . $contactType;
1711 if (NULL === self
::$greeting) {
1712 self
::$greeting = array();
1715 if (!CRM_Utils_Array
::value($index, self
::$greeting)) {
1716 $filterCondition = NULL;
1718 $filterVal = 'v.filter =';
1719 switch ($contactType) {
1728 case 'Organization':
1732 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1735 self
::$greeting[$index] = CRM_Core_OptionGroup
::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1738 return self
::$greeting[$index];
1742 * Construct array of default greeting values for contact type.
1746 * array reference of default greetings.
1748 public static function &greetingDefaults() {
1749 if (!self
::$greetingDefaults) {
1750 $defaultGreetings = array();
1751 $contactTypes = self
::get('CRM_Contact_DAO_Contact', 'contact_type', array(
1752 'keyColumn' => 'id',
1753 'labelColumn' => 'name',
1756 foreach ($contactTypes as $filter => $contactType) {
1757 $filterCondition = " AND (v.filter = 0 OR v.filter = $filter) AND v.is_default = 1 ";
1759 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1760 $tokenVal = CRM_Core_OptionGroup
::values($greeting, NULL, NULL, NULL, $filterCondition, 'label');
1761 $defaultGreetings[$contactType][$greeting] = $tokenVal;
1765 self
::$greetingDefaults = $defaultGreetings;
1768 return self
::$greetingDefaults;
1772 * Get all extensions.
1774 * The static array extensions
1776 * FIXME: This is called by civix but not by any core code. We
1777 * should provide an API call which civix can use instead.
1781 * array($fullyQualifiedName => $label) list of extensions
1783 public static function &getExtensions() {
1784 if (!self
::$extensions) {
1785 self
::$extensions = array();
1787 SELECT full_name, label
1788 FROM civicrm_extension
1791 $dao = CRM_Core_DAO
::executeQuery($sql);
1792 while ($dao->fetch()) {
1793 self
::$extensions[$dao->full_name
] = $dao->label
;
1797 return self
::$extensions;
1801 * Get all options values.
1803 * The static array option values is returned
1806 * @param bool $optionGroupName
1807 * Get All Option Group values- default is to get only active ones.
1810 * @param null $condition
1813 * array reference of all Option Group Name
1815 public static function accountOptionValues($optionGroupName, $id = NULL, $condition = NULL) {
1816 $cacheKey = $optionGroupName . '_' . $condition;
1817 if (empty(self
::$accountOptionValues[$cacheKey])) {
1818 self
::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup
::values($optionGroupName, FALSE, FALSE, FALSE, $condition);
1821 return CRM_Utils_Array
::value($id, self
::$accountOptionValues[$cacheKey]);
1824 return self
::$accountOptionValues[$cacheKey];
1828 * Fetch the list of active extensions of type 'module'
1830 * @param bool $fresh
1831 * Whether to forcibly reload extensions list from canonical store.
1834 * array(array('prefix' => $, 'file' => $))
1836 public static function getModuleExtensions($fresh = FALSE) {
1837 return CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles($fresh);
1842 * Get all tax rates.
1844 * The static array tax rates is returned
1847 * array list of tax rates with the financial type
1849 public static function getTaxRates() {
1850 if (!self
::$taxRates) {
1851 self
::$taxRates = array();
1853 SELECT fa.tax_rate, efa.entity_id
1854 FROM civicrm_entity_financial_account efa
1855 INNER JOIN civicrm_financial_account fa ON fa.id = efa.financial_account_id
1856 INNER JOIN civicrm_option_value cov ON cov.value = efa.account_relationship
1857 INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id
1858 WHERE efa.entity_table = 'civicrm_financial_type'
1859 AND cov.name = 'Sales Tax Account is'
1860 AND cog.name = 'account_relationship'
1861 AND fa.is_active = 1";
1862 $dao = CRM_Core_DAO
::executeQuery($sql);
1863 while ($dao->fetch()) {
1864 self
::$taxRates[$dao->entity_id
] = $dao->tax_rate
;
1868 return self
::$taxRates;