3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
30 * Stores all constants and pseudo constants for CRM application.
32 * examples of constants are "Contact Type" which will always be either
33 * 'Individual', 'Household', 'Organization'.
35 * pseudo constants are entities from the database whose values rarely
36 * change. examples are list of countries, states, location types,
39 * currently we're getting the data from the underlying database. this
40 * will be reworked to use caching.
42 * Note: All pseudoconstants should be uninitialized or default to NULL.
43 * This provides greater consistency/predictability after flushing.
46 * @copyright CiviCRM LLC (c) 2004-2014
50 class CRM_Core_PseudoConstant
{
53 * Static cache for pseudoconstant arrays
56 private static $cache;
59 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
64 private static $activityType;
70 private static $stateProvince;
76 private static $county;
79 * States/provinces abbreviations
82 private static $stateProvinceAbbreviation;
88 private static $country;
94 private static $countryIsoCode;
97 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
102 private static $group;
108 private static $groupIterator;
114 private static $relationshipType;
117 * Civicrm groups that are not smart groups
120 private static $staticGroup;
126 private static $currencyCode;
132 private static $paymentProcessor;
135 * Payment processor types
138 private static $paymentProcessorType;
144 private static $worldRegions;
147 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
152 private static $activityStatus;
158 private static $visibility;
164 private static $greeting;
170 private static $greetingDefaults;
173 * Extensions of type module
176 private static $extensions;
179 * Financial Account Type
182 private static $accountOptionValues;
188 private static $taxRates;
191 * Low-level option getter, rarely accessed directly.
192 * NOTE: Rather than calling this function directly use CRM_*_BAO_*::buildOptions()
193 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Pseudoconstant+%28option+list%29+Reference
195 * @param string $daoName
196 * @param string $fieldName
197 * @param array $params
198 * - name string name of the option group
199 * - flip boolean results are return in id => label format if false
200 * if true, the results are reversed
201 * - grouping boolean if true, return the value in 'grouping' column (currently unsupported for tables other than option_value)
202 * - localize boolean if true, localize the results before returning
203 * - condition string|array add condition(s) to the sql query - will be concatenated using 'AND'
204 * - keyColumn string the column to use for 'id'
205 * - labelColumn string the column to use for 'label'
206 * - orderColumn string the column to use for sorting, defaults to 'weight' column if one exists, else defaults to labelColumn
207 * - onlyActive boolean return only the action option values
208 * - fresh boolean ignore cache entries and go back to DB
209 * @param string $context : Context string
212 * array on success, FALSE on error.
215 public static function get($daoName, $fieldName, $params = array(), $context = NULL) {
216 CRM_Core_DAO
::buildOptionsContext($context);
217 $flip = !empty($params['flip']);
218 // Merge params with defaults
222 'onlyActive' => ($context == 'validate' ||
$context == 'get') ?
FALSE : TRUE,
226 // Custom fields are not in the schema
227 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
228 $customField = new CRM_Core_DAO_CustomField();
229 $customField->id
= (int) substr($fieldName, 7);
230 $customField->find(TRUE);
233 if (!empty($customField->option_group_id
)) {
234 $options = CRM_Core_OptionGroup
::valuesByID($customField->option_group_id
,
238 // Note: for custom fields the 'name' column is NULL
239 CRM_Utils_Array
::value('labelColumn', $params, 'label'),
240 $params['onlyActive'],
245 if ($customField->data_type
=== 'StateProvince') {
246 $options = self
::stateProvince();
248 elseif ($customField->data_type
=== 'Country') {
249 $options = $context == 'validate' ? self
::countryIsoCode() : self
::country();
251 elseif ($customField->data_type
=== 'Boolean') {
252 $options = $context == 'validate' ?
array(0, 1) : array(1 => ts('Yes'), 0 => ts('No'));
255 CRM_Utils_Hook
::customFieldOptions($customField->id
, $options, FALSE);
256 if ($options && $flip) {
257 $options = array_flip($options);
259 $customField->free();
263 // Core field: load schema
264 $dao = new $daoName();
265 $fieldSpec = $dao->getFieldSpec($fieldName);
267 // If neither worked then this field doesn't exist. Return false.
268 if (empty($fieldSpec)) {
272 elseif (!empty($fieldSpec['pseudoconstant'])) {
273 $pseudoconstant = $fieldSpec['pseudoconstant'];
275 // if callback is specified..
276 if (!empty($pseudoconstant['callback'])) {
277 list($className, $fnName) = explode('::', $pseudoconstant['callback']);
278 if (method_exists($className, $fnName)) {
279 return call_user_func(array($className, $fnName));
283 // Merge params with schema defaults
285 'condition' => CRM_Utils_Array
::value('condition', $pseudoconstant, array()),
286 'keyColumn' => CRM_Utils_Array
::value('keyColumn', $pseudoconstant),
287 'labelColumn' => CRM_Utils_Array
::value('labelColumn', $pseudoconstant),
290 if ($context == 'abbreviate') {
291 switch ($fieldName) {
292 case 'state_province_id':
293 $params['labelColumn'] = 'abbreviation';
296 $params['labelColumn'] = 'iso_code';
302 // Fetch option group from option_value table
303 if (!empty($pseudoconstant['optionGroupName'])) {
304 if ($context == 'validate') {
305 $params['labelColumn'] = 'name';
307 // Call our generic fn for retrieving from the option_value table
308 return CRM_Core_OptionGroup
::values(
309 $pseudoconstant['optionGroupName'],
313 $params['condition'] ?
' AND ' . implode(' AND ', (array) $params['condition']) : NULL,
314 $params['labelColumn'] ?
$params['labelColumn'] : 'label',
315 $params['onlyActive'],
317 $params['keyColumn'] ?
$params['keyColumn'] : 'value'
321 // Fetch options from other tables
322 if (!empty($pseudoconstant['table'])) {
323 // Normalize params so the serialized cache string will be consistent.
324 CRM_Utils_Array
::remove($params, 'flip', 'fresh');
326 $cacheKey = $daoName . $fieldName . serialize($params);
328 // Retrieve cached options
329 if (isset(self
::$cache[$cacheKey]) && empty($params['fresh'])) {
330 $output = self
::$cache[$cacheKey];
333 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($pseudoconstant['table']);
334 if (!class_exists($daoName)) {
337 // Get list of fields for the option table
338 $dao = new $daoName();
339 $availableFields = array_keys($dao->fieldKeys());
342 $select = "SELECT %1 AS id, %2 AS label";
345 $order = "ORDER BY %2";
347 // Use machine name instead of label in validate context
348 if ($context == 'validate') {
349 if (!empty($pseudoconstant['nameColumn'])) {
350 $params['labelColumn'] = $pseudoconstant['nameColumn'];
352 elseif (in_array('name', $availableFields)) {
353 $params['labelColumn'] = 'name';
356 // Condition param can be passed as an sql clause string or an array of clauses
357 if (!empty($params['condition'])) {
358 $wheres[] = implode(' AND ', (array) $params['condition']);
360 // onlyActive param will automatically filter on common flags
361 if (!empty($params['onlyActive'])) {
362 foreach (array('is_active' => 1, 'is_deleted' => 0, 'is_test' => 0) as $flag => $val) {
363 if (in_array($flag, $availableFields)) {
364 $wheres[] = "$flag = $val";
368 // Filter domain specific options
369 if (in_array('domain_id', $availableFields)) {
370 $wheres[] = 'domain_id = ' . CRM_Core_Config
::domainID();
372 $queryParams = array(
373 1 => array($params['keyColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
374 2 => array($params['labelColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
375 3 => array($pseudoconstant['table'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
377 // Add orderColumn param
378 if (!empty($params['orderColumn'])) {
379 $queryParams[4] = array($params['orderColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
);
380 $order = "ORDER BY %4";
382 // Support no sorting if $params[orderColumn] is FALSE
383 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
386 // Default to 'weight' if that column exists
387 elseif (in_array('weight', $availableFields)) {
388 $order = "ORDER BY weight";
392 $query = "$select $from";
394 $query .= " WHERE " . implode($wheres, ' AND ');
396 $query .= ' ' . $order;
397 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
398 while ($dao->fetch()) {
399 $output[$dao->id
] = $dao->label
;
403 if (!empty($params['localize']) ||
$pseudoconstant['table'] == 'civicrm_country' ||
$pseudoconstant['table'] == 'civicrm_state_province') {
404 $I18nParams = array();
405 if ($pseudoconstant['table'] == 'civicrm_country') {
406 $I18nParams['context'] = 'country';
408 if ($pseudoconstant['table'] == 'civicrm_state_province') {
409 $I18nParams['context'] = 'province';
411 $i18n = CRM_Core_I18n
::singleton();
412 $i18n->localizeArray($output, $I18nParams);
413 // Maintain sort by label
414 if ($order == "ORDER BY %2") {
415 CRM_Utils_Array
::asort($output);
418 self
::$cache[$cacheKey] = $output;
420 return $flip ?
array_flip($output) : $output;
424 // Return "Yes" and "No" for boolean fields
425 elseif (CRM_Utils_Array
::value('type', $fieldSpec) === CRM_Utils_Type
::T_BOOLEAN
) {
426 $output = $context == 'validate' ?
array(0, 1) : array(1 => ts('Yes'), 0 => ts('No'));
427 return $flip ?
array_flip($output) : $output;
429 // If we're still here, it's an error. Return FALSE.
434 * Fetch the translated label for a field given its key
436 * @param string $baoName
437 * @param string $fieldName
438 * @param string|Int $key
440 * TODO: Accept multivalued input?
442 * @return bool|null|string
443 * FALSE if the given field has no associated option list
444 * NULL if the given key has no corresponding option
445 * String if label is found
447 public static function getLabel($baoName, $fieldName, $key) {
448 $values = $baoName::buildOptions($fieldName, 'get');
449 if ($values === FALSE) {
452 return CRM_Utils_Array
::value($key, $values);
456 * Fetch the machine name for a field given its key
458 * @param string $baoName
459 * @param string $fieldName
460 * @param string|Int $key
462 * @return bool|null|string
463 * FALSE if the given field has no associated option list
464 * NULL if the given key has no corresponding option
465 * String if label is found
467 public static function getName($baoName, $fieldName, $key) {
468 $values = $baoName::buildOptions($fieldName, 'validate');
469 if ($values === FALSE) {
472 return CRM_Utils_Array
::value($key, $values);
476 * Fetch the key for a field option given its name
478 * @param string $baoName
479 * @param string $fieldName
480 * @param string|Int $value
482 * @return bool|null|string|int
483 * FALSE if the given field has no associated option list
484 * NULL if the given key has no corresponding option
485 * String|Number if key is found
487 public static function getKey($baoName, $fieldName, $value) {
488 $values = $baoName::buildOptions($fieldName, 'validate');
489 if ($values === FALSE) {
492 return CRM_Utils_Array
::key($value, $values);
496 * Lookup the admin page at which a field's option list can be edited
498 * @return string|null
500 public static function getOptionEditUrl($fieldSpec) {
501 // If it's an option group, that's easy
502 if (!empty($fieldSpec['pseudoconstant']['optionGroupName'])) {
503 return 'civicrm/admin/options/' . $fieldSpec['pseudoconstant']['optionGroupName'];
505 // For everything else...
506 elseif (!empty($fieldSpec['pseudoconstant']['table'])) {
507 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($fieldSpec['pseudoconstant']['table']);
511 // We don't have good mapping so have to do a bit of guesswork from the menu
512 list(, $parent, , $child) = explode('_', $daoName);
513 $sql = "SELECT path FROM civicrm_menu
514 WHERE page_callback LIKE '%CRM_Admin_Page_$child%' OR page_callback LIKE '%CRM_{$parent}_Page_$child%'
515 ORDER BY page_callback
517 return CRM_Core_Dao
::singleValueQuery($sql);
523 * DEPRECATED generic populate method
524 * All pseudoconstant functions that use this method are also @deprecated
526 * The static array $var is populated from the db
527 * using the <b>$name DAO</b>.
529 * Note: any database errors will be trapped by the DAO.
532 * The associative array we will fill.
533 * @param string $name
534 * The name of the DAO.
536 * Get all objects. default is to get only active ones.
537 * @param string $retrieve
538 * The field that we are interested in (normally name, differs in some objects).
539 * @param string $filter
540 * The field that we want to filter the result set with.
541 * @param string $condition
542 * The condition that gets passed to the final query as the WHERE clause.
544 * @param null $orderby
550 public static function populate(
555 $filter = 'is_active',
561 $cacheKey = "CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}";
562 $cache = CRM_Utils_Cache
::singleton();
563 $var = $cache->get($cacheKey);
564 if ($var && empty($force)) {
568 $object = new $name();
570 $object->selectAdd();
571 $object->selectAdd("$key, $retrieve");
573 $object->whereAdd($condition);
577 $object->orderBy($retrieve);
580 $object->orderBy($orderby);
584 $object->$filter = 1;
589 while ($object->fetch()) {
590 $var[$object->$key] = $object->$retrieve;
593 $cache->set($cacheKey, $var);
597 * Flush given pseudoconstant so it can be reread from db
598 * nex time it's requested.
601 * @param bool|string $name pseudoconstant to be flushed
603 public static function flush($name = 'cache') {
604 if (isset(self
::$
$name)) {
607 if ($name == 'cache') {
608 CRM_Core_OptionGroup
::flushAll();
613 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
615 * Get all Activty types.
617 * The static array activityType is returned
621 * array reference of all activity types.
623 public static function &activityType() {
624 $args = func_get_args();
625 $all = CRM_Utils_Array
::value(0, $args, TRUE);
626 $includeCaseActivities = CRM_Utils_Array
::value(1, $args, FALSE);
627 $reset = CRM_Utils_Array
::value(2, $args, FALSE);
628 $returnColumn = CRM_Utils_Array
::value(3, $args, 'label');
629 $includeCampaignActivities = CRM_Utils_Array
::value(4, $args, FALSE);
630 $onlyComponentActivities = CRM_Utils_Array
::value(5, $args, FALSE);
631 $index = (int) $all . '_' . $returnColumn . '_' . (int) $includeCaseActivities;
632 $index .= '_' . (int) $includeCampaignActivities;
633 $index .= '_' . (int) $onlyComponentActivities;
635 if (NULL === self
::$activityType) {
636 self
::$activityType = array();
639 if (!isset(self
::$activityType[$index]) ||
$reset) {
642 $condition = 'AND filter = 0';
644 $componentClause = " v.component_id IS NULL";
645 if ($onlyComponentActivities) {
646 $componentClause = " v.component_id IS NOT NULL";
649 $componentIds = array();
650 $compInfo = CRM_Core_Component
::getEnabledComponents();
652 // build filter for listing activity types only if their
653 // respective components are enabled
654 foreach ($compInfo as $compName => $compObj) {
655 if ($compName == 'CiviCase') {
656 if ($includeCaseActivities) {
657 $componentIds[] = $compObj->componentID
;
660 elseif ($compName == 'CiviCampaign') {
661 if ($includeCampaignActivities) {
662 $componentIds[] = $compObj->componentID
;
666 $componentIds[] = $compObj->componentID
;
670 if (count($componentIds)) {
671 $componentIds = implode(',', $componentIds);
672 $componentClause = " ($componentClause OR v.component_id IN ($componentIds))";
673 if ($onlyComponentActivities) {
674 $componentClause = " ( v.component_id IN ($componentIds ) )";
677 $condition = $condition . ' AND ' . $componentClause;
679 self
::$activityType[$index] = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
681 return self
::$activityType[$index];
685 * Get all the State/Province from database.
687 * The static array stateProvince is returned, and if it's
688 * called the first time, the <b>State Province DAO</b> is used
689 * to get all the States.
691 * Note: any database errors will be trapped by the DAO.
694 * @param bool|int $id - Optional id to return
699 * array reference of all State/Provinces.
701 public static function &stateProvince($id = FALSE, $limit = TRUE) {
702 if (($id && !CRM_Utils_Array
::value($id, self
::$stateProvince)) ||
!self
::$stateProvince ||
!$id) {
703 $whereClause = FALSE;
704 $config = CRM_Core_Config
::singleton();
706 $countryIsoCodes = self
::countryIsoCode();
707 $limitCodes = $config->provinceLimit();
709 foreach ($limitCodes as $code) {
710 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
712 if (!empty($limitIds)) {
713 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
716 $whereClause = FALSE;
719 self
::populate(self
::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
721 // localise the province names if in an non-en_US locale
723 if ($tsLocale != '' and $tsLocale != 'en_US') {
724 $i18n = CRM_Core_I18n
::singleton();
725 $i18n->localizeArray(self
::$stateProvince, array(
726 'context' => 'province',
728 self
::$stateProvince = CRM_Utils_Array
::asort(self
::$stateProvince);
732 if (array_key_exists($id, self
::$stateProvince)) {
733 return self
::$stateProvince[$id];
740 return self
::$stateProvince;
744 * Get all the State/Province abbreviations from the database.
746 * Same as above, except gets the abbreviations instead of the names.
749 * @param bool|int $id - Optional id to return
754 * array reference of all State/Province abbreviations.
756 public static function &stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
760 FROM civicrm_state_province
768 return CRM_Core_DAO
::singleValueQuery($query, $params);
771 if (!self
::$stateProvinceAbbreviation ||
!$id) {
773 $whereClause = FALSE;
776 $config = CRM_Core_Config
::singleton();
777 $countryIsoCodes = self
::countryIsoCode();
778 $limitCodes = $config->provinceLimit();
780 foreach ($limitCodes as $code) {
781 $tmpArray = array_keys($countryIsoCodes, $code);
783 if (!empty($tmpArray)) {
784 $limitIds[] = array_shift($tmpArray);
787 if (!empty($limitIds)) {
788 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
791 self
::populate(self
::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
795 if (array_key_exists($id, self
::$stateProvinceAbbreviation)) {
796 return self
::$stateProvinceAbbreviation[$id];
803 return self
::$stateProvinceAbbreviation;
807 * Get all the countries from database.
809 * The static array country is returned, and if it's
810 * called the first time, the <b>Country DAO</b> is used
811 * to get all the countries.
813 * Note: any database errors will be trapped by the DAO.
816 * @param bool|int $id - Optional id to return
818 * @param bool $applyLimit
821 * array reference of all countries.
823 public static function country($id = FALSE, $applyLimit = TRUE) {
824 if (($id && !CRM_Utils_Array
::value($id, self
::$country)) ||
!self
::$country ||
!$id) {
826 $config = CRM_Core_Config
::singleton();
827 $limitCodes = array();
830 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
831 // (ensuring it's a subset of the legal values)
832 // K/P: We need to fix this, i dont think it works with new setting files
833 $limitCodes = $config->countryLimit();
834 if (!is_array($limitCodes)) {
836 $config->countryLimit
=> 1,
840 $limitCodes = array_intersect(self
::countryIsoCode(), $limitCodes);
843 if (count($limitCodes)) {
844 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
850 self
::populate(self
::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
852 // if default country is set, percolate it to the top
853 if ($config->defaultContactCountry()) {
854 $countryIsoCodes = self
::countryIsoCode();
855 $defaultID = array_search($config->defaultContactCountry(), $countryIsoCodes);
856 if ($defaultID !== FALSE) {
857 $default[$defaultID] = CRM_Utils_Array
::value($defaultID, self
::$country);
858 self
::$country = $default + self
::$country;
862 // localise the country names if in an non-en_US locale
864 if ($tsLocale != '' and $tsLocale != 'en_US') {
865 $i18n = CRM_Core_I18n
::singleton();
866 $i18n->localizeArray(self
::$country, array(
867 'context' => 'country',
869 self
::$country = CRM_Utils_Array
::asort(self
::$country);
873 if (array_key_exists($id, self
::$country)) {
874 return self
::$country[$id];
877 return CRM_Core_DAO
::$_nullObject;
880 return self
::$country;
884 * Get all the country ISO Code abbreviations from the database.
886 * The static array countryIsoCode is returned, and if it's
887 * called the first time, the <b>Country DAO</b> is used
888 * to get all the countries' ISO codes.
890 * Note: any database errors will be trapped by the DAO.
896 * array reference of all country ISO codes.
898 public static function &countryIsoCode($id = FALSE) {
899 if (!self
::$countryIsoCode) {
900 self
::populate(self
::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
903 if (array_key_exists($id, self
::$countryIsoCode)) {
904 return self
::$countryIsoCode[$id];
907 return CRM_Core_DAO
::$_nullObject;
910 return self
::$countryIsoCode;
914 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
916 * Get all groups from database
918 * The static array group is returned, and if it's
919 * called the first time, the <b>Group DAO</b> is used
920 * to get all the groups.
922 * Note: any database errors will be trapped by the DAO.
924 * @param string $groupType
925 * Type of group(Access/Mailing).
926 * @param bool $excludeHidden
927 * Exclude hidden groups.
931 * array reference of all groups.
933 public static function &allGroup($groupType = NULL, $excludeHidden = TRUE) {
934 $condition = CRM_Contact_BAO_Group
::groupTypeCondition($groupType, $excludeHidden);
937 self
::$group = array();
940 $groupKey = $groupType ?
$groupType : 'null';
942 if (!isset(self
::$group[$groupKey])) {
943 self
::$group[$groupKey] = NULL;
944 self
::populate(self
::$group[$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
946 return self
::$group[$groupKey];
950 * Create or get groups iterator (iterates over nested groups in a
953 * The GroupNesting instance is returned; it's created if this is being
954 * called for the first time
958 * @param bool $styledLabels
960 * @return CRM_Contact_BAO_GroupNesting
962 public static function &groupIterator($styledLabels = FALSE) {
963 if (!self
::$groupIterator) {
964 // When used as an object, GroupNesting implements Iterator
965 // and iterates nested groups in a logical manner for us
966 self
::$groupIterator = new CRM_Contact_BAO_GroupNesting($styledLabels);
968 return self
::$groupIterator;
972 * Get all permissioned groups from database
974 * The static array group is returned, and if it's
975 * called the first time, the <b>Group DAO</b> is used
976 * to get all the groups.
978 * Note: any database errors will be trapped by the DAO.
980 * @param string $groupType
981 * Type of group(Access/Mailing).
982 * @param bool $excludeHidden
983 * Exclude hidden groups.
987 * array reference of all groups.
989 public static function group($groupType = NULL, $excludeHidden = TRUE) {
990 return CRM_Core_Permission
::group($groupType, $excludeHidden);
994 * Fetch groups in a nested format suitable for use in select form element
995 * @param bool $checkPermissions
996 * @param string|null $groupType
997 * @param bool $excludeHidden
1000 public static function nestedGroup($checkPermissions = TRUE, $groupType = NULL, $excludeHidden = TRUE) {
1001 $groups = $checkPermissions ? self
::group($groupType, $excludeHidden) : self
::allGroup($groupType, $excludeHidden);
1002 return CRM_Contact_BAO_Group
::getGroupsHierarchy($groups, NULL, ' ', TRUE);
1006 * Get all permissioned groups from database
1008 * The static array group is returned, and if it's
1009 * called the first time, the <b>Group DAO</b> is used
1010 * to get all the groups.
1012 * Note: any database errors will be trapped by the DAO.
1015 * @param bool $onlyPublic
1016 * @param null $groupType
1017 * @param bool $excludeHidden
1020 * array reference of all groups.
1022 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
1023 if (!self
::$staticGroup) {
1024 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
1026 $condition .= " AND visibility != 'User and User Admin Only'";
1030 $condition .= ' AND ' . CRM_Contact_BAO_Group
::groupTypeCondition($groupType);
1033 if ($excludeHidden) {
1034 $condition .= ' AND is_hidden != 1 ';
1037 self
::populate(self
::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
1040 return self
::$staticGroup;
1044 * Get all Relationship Types from database.
1046 * The static array group is returned, and if it's
1047 * called the first time, the <b>RelationshipType DAO</b> is used
1048 * to get all the relationship types.
1050 * Note: any database errors will be trapped by the DAO.
1052 * @param string $valueColumnName
1053 * Db column name/label.
1054 * @param bool $reset
1055 * Reset relationship types if true.
1059 * array reference of all relationship types.
1061 public static function &relationshipType($valueColumnName = 'label', $reset = FALSE) {
1062 if (!CRM_Utils_Array
::value($valueColumnName, self
::$relationshipType) ||
$reset) {
1063 self
::$relationshipType[$valueColumnName] = array();
1065 //now we have name/label columns CRM-3336
1066 $column_a_b = "{$valueColumnName}_a_b";
1067 $column_b_a = "{$valueColumnName}_b_a";
1069 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1070 $relationshipTypeDAO->selectAdd();
1071 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1072 $relationshipTypeDAO->is_active
= 1;
1073 $relationshipTypeDAO->find();
1074 while ($relationshipTypeDAO->fetch()) {
1076 self
::$relationshipType[$valueColumnName][$relationshipTypeDAO->id
] = array(
1077 'id' => $relationshipTypeDAO->id
,
1078 $column_a_b => $relationshipTypeDAO->$column_a_b,
1079 $column_b_a => $relationshipTypeDAO->$column_b_a,
1080 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1081 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1082 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1083 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1088 return self
::$relationshipType[$valueColumnName];
1092 * Get all the ISO 4217 currency codes
1094 * so far, we use this for validation only, so there's no point of putting this into the database
1098 * array reference of all currency codes
1100 public static function ¤cyCode() {
1101 if (!self
::$currencyCode) {
1102 self
::$currencyCode = array(
1372 return self
::$currencyCode;
1376 * Get all the County from database.
1378 * The static array county is returned, and if it's
1379 * called the first time, the <b>County DAO</b> is used
1380 * to get all the Counties.
1382 * Note: any database errors will be trapped by the DAO.
1385 * @param bool|int $id - Optional id to return
1388 * array reference of all Counties
1390 public static function &county($id = FALSE) {
1391 if (!self
::$county) {
1393 $config = CRM_Core_Config
::singleton();
1394 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1395 self
::populate(self
::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1398 if (array_key_exists($id, self
::$county)) {
1399 return self
::$county[$id];
1402 return CRM_Core_DAO
::$_nullObject;
1405 return self
::$county;
1409 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1410 * Get all active payment processors
1412 * The static array paymentProcessor is returned
1416 * Get payment processors - default is to get only active ones.
1418 * Get test payment processors.
1420 * @param null $additionalCond
1423 * array of all payment processors
1425 public static function &paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1426 $condition = "is_test = ";
1427 $condition .= ($test) ?
'1' : '0';
1429 if ($additionalCond) {
1430 $condition .= " AND ( $additionalCond ) ";
1433 // CRM-7178. Make sure we only include payment processors valid in ths
1435 $condition .= " AND domain_id = " . CRM_Core_Config
::domainID();
1437 $cacheKey = $condition . '_' . (int) $all;
1438 if (!isset(self
::$paymentProcessor[$cacheKey])) {
1439 self
::populate(self
::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1442 return self
::$paymentProcessor[$cacheKey];
1446 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1448 * The static array paymentProcessorType is returned
1452 * Get payment processors - default is to get only active ones.
1455 * @param string $return
1458 * array of all payment processor types
1460 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1461 $cacheKey = $id . '_' . $return;
1462 if (empty(self
::$paymentProcessorType[$cacheKey])) {
1463 self
::populate(self
::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1465 if ($id && CRM_Utils_Array
::value($id, self
::$paymentProcessorType[$cacheKey])) {
1466 return self
::$paymentProcessorType[$cacheKey][$id];
1468 return self
::$paymentProcessorType[$cacheKey];
1472 * Get all the World Regions from Database
1478 * array reference of all World Regions
1480 public static function &worldRegion($id = FALSE) {
1481 if (!self
::$worldRegions) {
1482 self
::populate(self
::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1486 if (array_key_exists($id, self
::$worldRegions)) {
1487 return self
::$worldRegions[$id];
1490 return CRM_Core_DAO
::$_nullObject;
1494 return self
::$worldRegions;
1498 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1500 * Get all Activity Statuses.
1502 * The static array activityStatus is returned
1505 * @param string $column
1508 * array reference of all activity statuses
1510 public static function &activityStatus($column = 'label') {
1511 if (NULL === self
::$activityStatus) {
1512 self
::$activityStatus = array();
1514 if (!array_key_exists($column, self
::$activityStatus)) {
1515 self
::$activityStatus[$column] = array();
1517 self
::$activityStatus[$column] = CRM_Core_OptionGroup
::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1520 return self
::$activityStatus[$column];
1524 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1526 * Get all Visibility levels.
1528 * The static array visibility is returned
1531 * @param string $column
1534 * array reference of all Visibility levels.
1536 public static function &visibility($column = 'label') {
1537 if (!isset(self
::$visibility)) {
1538 self
::$visibility = array();
1541 if (!isset(self
::$visibility[$column])) {
1542 self
::$visibility[$column] = CRM_Core_OptionGroup
::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1545 return self
::$visibility[$column];
1549 * @param int $countryID
1550 * @param string $field
1554 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1555 static $_cache = NULL;
1557 $cacheKey = "{$countryID}_{$field}";
1562 if (!empty($_cache[$cacheKey])) {
1563 return $_cache[$cacheKey];
1567 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1568 FROM civicrm_state_province
1569 WHERE country_id = %1
1578 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1581 while ($dao->fetch()) {
1582 $result[$dao->id
] = $dao->name
;
1585 // localise the stateProvince names if in an non-en_US locale
1586 $config = CRM_Core_Config
::singleton();
1588 if ($tsLocale != '' and $tsLocale != 'en_US') {
1589 $i18n = CRM_Core_I18n
::singleton();
1590 $i18n->localizeArray($result, array(
1591 'context' => 'province',
1593 $result = CRM_Utils_Array
::asort($result);
1596 $_cache[$cacheKey] = $result;
1598 CRM_Utils_Hook
::buildStateProvinceForCountry($countryID, $result);
1604 * @param int $stateID
1608 public static function &countyForState($stateID) {
1609 if (is_array($stateID)) {
1610 $states = implode(", ", $stateID);
1612 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1614 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1615 WHERE civicrm_county.state_province_id in ( $states )
1616 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1618 $dao = CRM_Core_DAO
::executeQuery($query);
1621 while ($dao->fetch()) {
1622 $result[$dao->id
] = $dao->abbreviation
. ': ' . $dao->name
;
1627 static $_cache = NULL;
1629 $cacheKey = "{$stateID}_name";
1634 if (!empty($_cache[$cacheKey])) {
1635 return $_cache[$cacheKey];
1639 SELECT civicrm_county.name name, civicrm_county.id id
1641 WHERE state_province_id = %1
1650 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1653 while ($dao->fetch()) {
1654 $result[$dao->id
] = $dao->name
;
1662 * Given a state ID return the country ID, this allows
1663 * us to populate forms and values for downstream code
1665 * @param int $stateID
1668 * the country id that the state belongs to
1670 public static function countryIDForStateID($stateID) {
1671 if (empty($stateID)) {
1672 return CRM_Core_DAO
::$_nullObject;
1677 FROM civicrm_state_province
1680 $params = array(1 => array($stateID, 'Integer'));
1682 return CRM_Core_DAO
::singleValueQuery($query, $params);
1686 * Get all types of Greetings.
1688 * The static array of greeting is returned
1692 * Get All Email Greetings - default is to get only active ones.
1694 * @param string $columnName
1697 * array reference of all greetings.
1699 public static function greeting($filter, $columnName = 'label') {
1700 $index = $filter['greeting_type'] . '_' . $columnName;
1702 // also add contactType to the array
1703 $contactType = CRM_Utils_Array
::value('contact_type', $filter);
1705 $index .= '_' . $contactType;
1708 if (NULL === self
::$greeting) {
1709 self
::$greeting = array();
1712 if (!CRM_Utils_Array
::value($index, self
::$greeting)) {
1713 $filterCondition = NULL;
1715 $filterVal = 'v.filter =';
1716 switch ($contactType) {
1725 case 'Organization':
1729 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1732 self
::$greeting[$index] = CRM_Core_OptionGroup
::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1735 return self
::$greeting[$index];
1739 * Construct array of default greeting values for contact type
1743 * array reference of default greetings.
1745 public static function &greetingDefaults() {
1746 if (!self
::$greetingDefaults) {
1747 $defaultGreetings = array();
1748 $contactTypes = self
::get('CRM_Contact_DAO_Contact', 'contact_type', array(
1749 'keyColumn' => 'id',
1750 'labelColumn' => 'name',
1753 foreach ($contactTypes as $filter => $contactType) {
1754 $filterCondition = " AND (v.filter = 0 OR v.filter = $filter) AND v.is_default = 1 ";
1756 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1757 $tokenVal = CRM_Core_OptionGroup
::values($greeting, NULL, NULL, NULL, $filterCondition, 'label');
1758 $defaultGreetings[$contactType][$greeting] = $tokenVal;
1762 self
::$greetingDefaults = $defaultGreetings;
1765 return self
::$greetingDefaults;
1769 * Get all extensions
1771 * The static array extensions
1773 * FIXME: This is called by civix but not by any core code. We
1774 * should provide an API call which civix can use instead.
1778 * array($fullyQualifiedName => $label) list of extensions
1780 public static function &getExtensions() {
1781 if (!self
::$extensions) {
1782 self
::$extensions = array();
1784 SELECT full_name, label
1785 FROM civicrm_extension
1788 $dao = CRM_Core_DAO
::executeQuery($sql);
1789 while ($dao->fetch()) {
1790 self
::$extensions[$dao->full_name
] = $dao->label
;
1794 return self
::$extensions;
1798 * Get all options values
1800 * The static array option values is returned
1803 * @param bool $optionGroupName
1804 * Get All Option Group values- default is to get only active ones.
1807 * @param null $condition
1810 * array reference of all Option Group Name
1812 public static function accountOptionValues($optionGroupName, $id = NULL, $condition = NULL) {
1813 $cacheKey = $optionGroupName . '_' . $condition;
1814 if (empty(self
::$accountOptionValues[$cacheKey])) {
1815 self
::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup
::values($optionGroupName, FALSE, FALSE, FALSE, $condition);
1818 return CRM_Utils_Array
::value($id, self
::$accountOptionValues[$cacheKey]);
1821 return self
::$accountOptionValues[$cacheKey];
1825 * Fetch the list of active extensions of type 'module'
1827 * @param bool $fresh
1828 * Whether to forcibly reload extensions list from canonical store.
1831 * array(array('prefix' => $, 'file' => $))
1833 public static function getModuleExtensions($fresh = FALSE) {
1834 return CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles($fresh);
1841 * The static array tax rates is returned
1844 * array list of tax rates with the financial type
1846 public static function getTaxRates() {
1847 if (!self
::$taxRates) {
1848 self
::$taxRates = array();
1850 SELECT fa.tax_rate, efa.entity_id
1851 FROM civicrm_entity_financial_account efa
1852 INNER JOIN civicrm_financial_account fa ON fa.id = efa.financial_account_id
1853 INNER JOIN civicrm_option_value cov ON cov.value = efa.account_relationship
1854 INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id
1855 WHERE efa.entity_table = 'civicrm_financial_type'
1856 AND cov.name = 'Sales Tax Account is'
1857 AND cog.name = 'account_relationship'
1858 AND fa.is_active = 1";
1859 $dao = CRM_Core_DAO
::executeQuery($sql);
1860 while ($dao->fetch()) {
1861 self
::$taxRates[$dao->entity_id
] = $dao->tax_rate
;
1865 return self
::$taxRates;