3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
48 class CRM_Core_PseudoConstant
{
51 * Static cache for pseudoconstant arrays.
54 private static $cache;
57 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
62 private static $activityType;
68 private static $stateProvince;
74 private static $county;
77 * States/provinces abbreviations
80 private static $stateProvinceAbbreviation = array();
86 private static $country;
92 private static $countryIsoCode;
95 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
100 private static $group;
106 private static $groupIterator;
112 private static $relationshipType;
115 * Civicrm groups that are not smart groups
118 private static $staticGroup;
124 private static $currencyCode;
130 private static $paymentProcessor;
133 * Payment processor types
136 private static $paymentProcessorType;
142 private static $worldRegions;
145 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
150 private static $activityStatus;
156 private static $visibility;
162 private static $greeting;
168 private static $greetingDefaults;
171 * Extensions of type module
174 private static $extensions;
177 * Financial Account Type
180 private static $accountOptionValues;
183 * Low-level option getter, rarely accessed directly.
184 * NOTE: Rather than calling this function directly use CRM_*_BAO_*::buildOptions()
185 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Pseudoconstant+%28option+list%29+Reference
187 * NOTE: If someone undertakes a refactoring of this, please consider the use-case of
188 * the Setting.getoptions API. There is no DAO/field, but it would be nice to use the
189 * same 'pseudoconstant' struct in *.settings.php. This means loosening the coupling
190 * between $field lookup and the $pseudoconstant evaluation.
192 * @param string $daoName
193 * @param string $fieldName
194 * @param array $params
195 * - name string name of the option group
196 * - flip boolean results are return in id => label format if false
197 * if true, the results are reversed
198 * - grouping boolean if true, return the value in 'grouping' column (currently unsupported for tables other than option_value)
199 * - localize boolean if true, localize the results before returning
200 * - condition string|array add condition(s) to the sql query - will be concatenated using 'AND'
201 * - keyColumn string the column to use for 'id'
202 * - labelColumn string the column to use for 'label'
203 * - orderColumn string the column to use for sorting, defaults to 'weight' column if one exists, else defaults to labelColumn
204 * - onlyActive boolean return only the action option values
205 * - fresh boolean ignore cache entries and go back to DB
206 * @param string $context : Context string
209 * array on success, FALSE on error.
212 public static function get($daoName, $fieldName, $params = array(), $context = NULL) {
213 CRM_Core_DAO
::buildOptionsContext($context);
214 $flip = !empty($params['flip']);
215 // Merge params with defaults
219 'onlyActive' => ($context == 'validate' ||
$context == 'get') ?
FALSE : TRUE,
221 'context' => $context,
223 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getCanonicalClassName($daoName));
225 // Custom fields are not in the schema
226 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
227 $customField = new CRM_Core_BAO_CustomField();
228 $customField->id
= (int) substr($fieldName, 7);
229 $options = $customField->getOptions();
230 if ($options && $flip) {
231 $options = array_flip($options);
233 $customField->free();
237 // Core field: load schema
238 $dao = new $daoName();
239 $fieldSpec = $dao->getFieldSpec($fieldName);
242 // Ensure we have the canonical name for this field
243 $fieldName = CRM_Utils_Array
::value('name', $fieldSpec, $fieldName);
245 // Return false if field doesn't exist.
246 if (empty($fieldSpec)) {
250 elseif (!empty($fieldSpec['pseudoconstant'])) {
251 $pseudoconstant = $fieldSpec['pseudoconstant'];
253 // if callback is specified..
254 if (!empty($pseudoconstant['callback'])) {
255 $fieldOptions = call_user_func(Civi\Core\Resolver
::singleton()->get($pseudoconstant['callback']));
256 //CRM-18223: Allow additions to field options via hook.
257 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $fieldOptions, $params);
258 return $fieldOptions;
261 // Merge params with schema defaults
263 'condition' => CRM_Utils_Array
::value('condition', $pseudoconstant, array()),
264 'keyColumn' => CRM_Utils_Array
::value('keyColumn', $pseudoconstant),
265 'labelColumn' => CRM_Utils_Array
::value('labelColumn', $pseudoconstant),
268 if ($context == 'abbreviate') {
269 switch ($fieldName) {
270 case 'state_province_id':
271 $params['labelColumn'] = 'abbreviation';
275 $params['labelColumn'] = 'iso_code';
282 // Fetch option group from option_value table
283 if (!empty($pseudoconstant['optionGroupName'])) {
284 if ($context == 'validate') {
285 $params['labelColumn'] = 'name';
287 if ($context == 'match') {
288 $params['keyColumn'] = 'name';
290 // Call our generic fn for retrieving from the option_value table
291 $options = CRM_Core_OptionGroup
::values(
292 $pseudoconstant['optionGroupName'],
296 $params['condition'] ?
' AND ' . implode(' AND ', (array) $params['condition']) : NULL,
297 $params['labelColumn'] ?
$params['labelColumn'] : 'label',
298 $params['onlyActive'],
300 $params['keyColumn'] ?
$params['keyColumn'] : 'value',
301 !empty($params['orderColumn']) ?
$params['orderColumn'] : 'weight'
303 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $options, $params);
307 // Fetch options from other tables
308 if (!empty($pseudoconstant['table'])) {
309 // Normalize params so the serialized cache string will be consistent.
310 CRM_Utils_Array
::remove($params, 'flip', 'fresh');
312 $cacheKey = $daoName . $fieldName . serialize($params);
314 // Retrieve cached options
315 if (isset(self
::$cache[$cacheKey]) && empty($params['fresh'])) {
316 $output = self
::$cache[$cacheKey];
319 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($pseudoconstant['table']);
320 if (!class_exists($daoName)) {
323 // Get list of fields for the option table
324 $dao = new $daoName();
325 $availableFields = array_keys($dao->fieldKeys());
328 $select = "SELECT %1 AS id, %2 AS label";
331 $order = "ORDER BY %2";
333 // Use machine name in certain contexts
334 if ($context == 'validate' ||
$context == 'match') {
335 $nameField = $context == 'validate' ?
'labelColumn' : 'keyColumn';
336 if (!empty($pseudoconstant['nameColumn'])) {
337 $params[$nameField] = $pseudoconstant['nameColumn'];
339 elseif (in_array('name', $availableFields)) {
340 $params[$nameField] = 'name';
343 // Condition param can be passed as an sql clause string or an array of clauses
344 if (!empty($params['condition'])) {
345 $wheres[] = implode(' AND ', (array) $params['condition']);
347 // onlyActive param will automatically filter on common flags
348 if (!empty($params['onlyActive'])) {
349 foreach (array('is_active' => 1, 'is_deleted' => 0, 'is_test' => 0, 'is_hidden' => 0) as $flag => $val) {
350 if (in_array($flag, $availableFields)) {
351 $wheres[] = "$flag = $val";
355 // Filter domain specific options
356 if (in_array('domain_id', $availableFields)) {
357 $wheres[] = 'domain_id = ' . CRM_Core_Config
::domainID();
359 $queryParams = array(
360 1 => array($params['keyColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
361 2 => array($params['labelColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
362 3 => array($pseudoconstant['table'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
364 // Add orderColumn param
365 if (!empty($params['orderColumn'])) {
366 $queryParams[4] = array($params['orderColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
);
367 $order = "ORDER BY %4";
369 // Support no sorting if $params[orderColumn] is FALSE
370 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
373 // Default to 'weight' if that column exists
374 elseif (in_array('weight', $availableFields)) {
375 $order = "ORDER BY weight";
379 $query = "$select $from";
381 $query .= " WHERE " . implode($wheres, ' AND ');
383 $query .= ' ' . $order;
384 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
385 while ($dao->fetch()) {
386 $output[$dao->id
] = $dao->label
;
390 if (!empty($params['localize']) ||
$pseudoconstant['table'] == 'civicrm_country' ||
$pseudoconstant['table'] == 'civicrm_state_province') {
391 $I18nParams = array();
392 if ($pseudoconstant['table'] == 'civicrm_country') {
393 $I18nParams['context'] = 'country';
395 if ($pseudoconstant['table'] == 'civicrm_state_province') {
396 $I18nParams['context'] = 'province';
398 $i18n = CRM_Core_I18n
::singleton();
399 $i18n->localizeArray($output, $I18nParams);
400 // Maintain sort by label
401 if ($order == "ORDER BY %2") {
402 CRM_Utils_Array
::asort($output);
405 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $output, $params);
406 self
::$cache[$cacheKey] = $output;
408 return $flip ?
array_flip($output) : $output;
412 // Return "Yes" and "No" for boolean fields
413 elseif (CRM_Utils_Array
::value('type', $fieldSpec) === CRM_Utils_Type
::T_BOOLEAN
) {
414 $output = $context == 'validate' ?
array(0, 1) : CRM_Core_SelectValues
::boolean();
415 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $output, $params);
416 return $flip ?
array_flip($output) : $output;
418 // If we're still here, it's an error. Return FALSE.
423 * Fetch the translated label for a field given its key.
425 * @param string $baoName
426 * @param string $fieldName
427 * @param string|Int $key
429 * TODO: Accept multivalued input?
431 * @return bool|null|string
432 * FALSE if the given field has no associated option list
433 * NULL if the given key has no corresponding option
434 * String if label is found
436 public static function getLabel($baoName, $fieldName, $key) {
437 $values = $baoName::buildOptions($fieldName, 'get');
438 if ($values === FALSE) {
441 return CRM_Utils_Array
::value($key, $values);
445 * Fetch the machine name for a field given its key.
447 * @param string $baoName
448 * @param string $fieldName
449 * @param string|Int $key
451 * @return bool|null|string
452 * FALSE if the given field has no associated option list
453 * NULL if the given key has no corresponding option
454 * String if label is found
456 public static function getName($baoName, $fieldName, $key) {
457 $values = $baoName::buildOptions($fieldName, 'validate');
458 if ($values === FALSE) {
461 return CRM_Utils_Array
::value($key, $values);
465 * Fetch the key for a field option given its name.
467 * @param string $baoName
468 * @param string $fieldName
469 * @param string|Int $value
471 * @return bool|null|string|int
472 * FALSE if the given field has no associated option list
473 * NULL if the given key has no corresponding option
474 * String|Number if key is found
476 public static function getKey($baoName, $fieldName, $value) {
477 $values = $baoName::buildOptions($fieldName, 'validate');
478 if ($values === FALSE) {
481 return CRM_Utils_Array
::key($value, $values);
485 * Lookup the admin page at which a field's option list can be edited
487 * @return string|null
489 public static function getOptionEditUrl($fieldSpec) {
490 // If it's an option group, that's easy
491 if (!empty($fieldSpec['pseudoconstant']['optionGroupName'])) {
492 return 'civicrm/admin/options/' . $fieldSpec['pseudoconstant']['optionGroupName'];
494 // For everything else...
495 elseif (!empty($fieldSpec['pseudoconstant']['table'])) {
496 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($fieldSpec['pseudoconstant']['table']);
500 // We don't have good mapping so have to do a bit of guesswork from the menu
501 list(, $parent, , $child) = explode('_', $daoName);
502 $sql = "SELECT path FROM civicrm_menu
503 WHERE page_callback LIKE '%CRM_Admin_Page_$child%' OR page_callback LIKE '%CRM_{$parent}_Page_$child%'
504 ORDER BY page_callback
506 return CRM_Core_Dao
::singleValueQuery($sql);
512 * DEPRECATED generic populate method.
513 * All pseudoconstant functions that use this method are also @deprecated
515 * The static array $var is populated from the db
516 * using the <b>$name DAO</b>.
518 * Note: any database errors will be trapped by the DAO.
521 * The associative array we will fill.
522 * @param string $name
523 * The name of the DAO.
525 * Get all objects. default is to get only active ones.
526 * @param string $retrieve
527 * The field that we are interested in (normally name, differs in some objects).
528 * @param string $filter
529 * The field that we want to filter the result set with.
530 * @param string $condition
531 * The condition that gets passed to the final query as the WHERE clause.
533 * @param bool $orderby
539 public static function populate(
544 $filter = 'is_active',
550 $cacheKey = "CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}";
551 $cache = CRM_Utils_Cache
::singleton();
552 $var = $cache->get($cacheKey);
553 if ($var && empty($force)) {
557 $object = new $name();
559 $object->selectAdd();
560 $object->selectAdd("$key, $retrieve");
562 $object->whereAdd($condition);
566 $object->orderBy($retrieve);
569 $object->orderBy($orderby);
573 $object->$filter = 1;
578 while ($object->fetch()) {
579 $var[$object->$key] = $object->$retrieve;
582 $cache->set($cacheKey, $var);
586 * Flush given pseudoconstant so it can be reread from db.
587 * nex time it's requested.
590 * @param bool|string $name pseudoconstant to be flushed
592 public static function flush($name = 'cache') {
593 if (isset(self
::$
$name)) {
596 if ($name == 'cache') {
597 CRM_Core_OptionGroup
::flushAll();
602 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
604 * Get all Activty types.
606 * The static array activityType is returned
610 * array reference of all activity types.
612 public static function &activityType() {
613 $args = func_get_args();
614 $all = CRM_Utils_Array
::value(0, $args, TRUE);
615 $includeCaseActivities = CRM_Utils_Array
::value(1, $args, FALSE);
616 $reset = CRM_Utils_Array
::value(2, $args, FALSE);
617 $returnColumn = CRM_Utils_Array
::value(3, $args, 'label');
618 $includeCampaignActivities = CRM_Utils_Array
::value(4, $args, FALSE);
619 $onlyComponentActivities = CRM_Utils_Array
::value(5, $args, FALSE);
620 $index = (int) $all . '_' . $returnColumn . '_' . (int) $includeCaseActivities;
621 $index .= '_' . (int) $includeCampaignActivities;
622 $index .= '_' . (int) $onlyComponentActivities;
624 if (NULL === self
::$activityType) {
625 self
::$activityType = array();
628 if (!isset(self
::$activityType[$index]) ||
$reset) {
631 $condition = 'AND filter = 0';
633 $componentClause = " v.component_id IS NULL";
634 if ($onlyComponentActivities) {
635 $componentClause = " v.component_id IS NOT NULL";
638 $componentIds = array();
639 $compInfo = CRM_Core_Component
::getEnabledComponents();
641 // build filter for listing activity types only if their
642 // respective components are enabled
643 foreach ($compInfo as $compName => $compObj) {
644 if ($compName == 'CiviCase') {
645 if ($includeCaseActivities) {
646 $componentIds[] = $compObj->componentID
;
649 elseif ($compName == 'CiviCampaign') {
650 if ($includeCampaignActivities) {
651 $componentIds[] = $compObj->componentID
;
655 $componentIds[] = $compObj->componentID
;
659 if (count($componentIds)) {
660 $componentIds = implode(',', $componentIds);
661 $componentClause = " ($componentClause OR v.component_id IN ($componentIds))";
662 if ($onlyComponentActivities) {
663 $componentClause = " ( v.component_id IN ($componentIds ) )";
666 $condition = $condition . ' AND ' . $componentClause;
668 self
::$activityType[$index] = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
670 return self
::$activityType[$index];
674 * Get all the State/Province from database.
676 * The static array stateProvince is returned, and if it's
677 * called the first time, the <b>State Province DAO</b> is used
678 * to get all the States.
680 * Note: any database errors will be trapped by the DAO.
683 * @param bool|int $id - Optional id to return
688 * array reference of all State/Provinces.
690 public static function &stateProvince($id = FALSE, $limit = TRUE) {
691 if (($id && !CRM_Utils_Array
::value($id, self
::$stateProvince)) ||
!self
::$stateProvince ||
!$id) {
692 $whereClause = FALSE;
694 $countryIsoCodes = self
::countryIsoCode();
695 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
697 foreach ($limitCodes as $code) {
698 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
700 if (!empty($limitIds)) {
701 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
704 $whereClause = FALSE;
707 self
::populate(self
::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
709 // localise the province names if in an non-en_US locale
711 if ($tsLocale != '' and $tsLocale != 'en_US') {
712 $i18n = CRM_Core_I18n
::singleton();
713 $i18n->localizeArray(self
::$stateProvince, array(
714 'context' => 'province',
716 self
::$stateProvince = CRM_Utils_Array
::asort(self
::$stateProvince);
720 if (array_key_exists($id, self
::$stateProvince)) {
721 return self
::$stateProvince[$id];
728 return self
::$stateProvince;
732 * Get all the State/Province abbreviations from the database.
734 * Same as above, except gets the abbreviations instead of the names.
737 * @param bool|int $id - Optional id to return
742 * array reference of all State/Province abbreviations.
744 public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
745 if ($id && is_numeric($id)) {
746 if (!array_key_exists($id, (array) self
::$stateProvinceAbbreviation)) {
747 $query = "SELECT abbreviation
748 FROM civicrm_state_province
756 self
::$stateProvinceAbbreviation[$id] = CRM_Core_DAO
::singleValueQuery($query, $params);
758 return self
::$stateProvinceAbbreviation[$id];
761 $whereClause = FALSE;
764 $countryIsoCodes = self
::countryIsoCode();
765 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
767 foreach ($limitCodes as $code) {
768 $tmpArray = array_keys($countryIsoCodes, $code);
770 if (!empty($tmpArray)) {
771 $limitIds[] = array_shift($tmpArray);
774 if (!empty($limitIds)) {
775 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
778 self
::populate(self
::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
781 return self
::$stateProvinceAbbreviation;
785 * Get all the countries from database.
787 * The static array country is returned, and if it's
788 * called the first time, the <b>Country DAO</b> is used
789 * to get all the countries.
791 * Note: any database errors will be trapped by the DAO.
794 * @param bool|int $id - Optional id to return
796 * @param bool $applyLimit
799 * array reference of all countries.
801 public static function country($id = FALSE, $applyLimit = TRUE) {
802 if (($id && !CRM_Utils_Array
::value($id, self
::$country)) ||
!self
::$country ||
!$id) {
804 $config = CRM_Core_Config
::singleton();
805 $limitCodes = array();
808 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
809 // (ensuring it's a subset of the legal values)
810 // K/P: We need to fix this, i dont think it works with new setting files
811 $limitCodes = CRM_Core_BAO_Country
::countryLimit();
812 if (!is_array($limitCodes)) {
814 $config->countryLimit
=> 1,
818 $limitCodes = array_intersect(self
::countryIsoCode(), $limitCodes);
821 if (count($limitCodes)) {
822 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
828 self
::populate(self
::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
830 // if default country is set, percolate it to the top
831 if ($config->defaultContactCountry()) {
832 $countryIsoCodes = self
::countryIsoCode();
833 $defaultID = array_search($config->defaultContactCountry(), $countryIsoCodes);
834 if ($defaultID !== FALSE) {
835 $default[$defaultID] = CRM_Utils_Array
::value($defaultID, self
::$country);
836 self
::$country = $default + self
::$country;
840 // localise the country names if in an non-en_US locale
842 if ($tsLocale != '' and $tsLocale != 'en_US') {
843 $i18n = CRM_Core_I18n
::singleton();
844 $i18n->localizeArray(self
::$country, array(
845 'context' => 'country',
847 self
::$country = CRM_Utils_Array
::asort(self
::$country);
851 if (array_key_exists($id, self
::$country)) {
852 return self
::$country[$id];
855 return CRM_Core_DAO
::$_nullObject;
858 return self
::$country;
862 * Get all the country ISO Code abbreviations from the database.
864 * The static array countryIsoCode is returned, and if it's
865 * called the first time, the <b>Country DAO</b> is used
866 * to get all the countries' ISO codes.
868 * Note: any database errors will be trapped by the DAO.
874 * array reference of all country ISO codes.
876 public static function &countryIsoCode($id = FALSE) {
877 if (!self
::$countryIsoCode) {
878 self
::populate(self
::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
881 if (array_key_exists($id, self
::$countryIsoCode)) {
882 return self
::$countryIsoCode[$id];
885 return CRM_Core_DAO
::$_nullObject;
888 return self
::$countryIsoCode;
892 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
894 * Get all groups from database
896 * The static array group is returned, and if it's
897 * called the first time, the <b>Group DAO</b> is used
898 * to get all the groups.
900 * Note: any database errors will be trapped by the DAO.
902 * @param string $groupType
903 * Type of group(Access/Mailing).
904 * @param bool $excludeHidden
905 * Exclude hidden groups.
909 * array reference of all groups.
911 public static function allGroup($groupType = NULL, $excludeHidden = TRUE) {
912 $condition = CRM_Contact_BAO_Group
::groupTypeCondition($groupType, $excludeHidden);
915 self
::$group = array();
918 $groupKey = ($groupType ?
$groupType : 'null') . !empty($excludeHidden);
920 if (!isset(self
::$group[$groupKey])) {
921 self
::$group[$groupKey] = NULL;
922 self
::populate(self
::$group[$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
924 return self
::$group[$groupKey];
928 * Create or get groups iterator (iterates over nested groups in a
931 * The GroupNesting instance is returned; it's created if this is being
932 * called for the first time
936 * @param bool $styledLabels
938 * @return CRM_Contact_BAO_GroupNesting
940 public static function &groupIterator($styledLabels = FALSE) {
941 if (!self
::$groupIterator) {
942 // When used as an object, GroupNesting implements Iterator
943 // and iterates nested groups in a logical manner for us
944 self
::$groupIterator = new CRM_Contact_BAO_GroupNesting($styledLabels);
946 return self
::$groupIterator;
950 * Get all permissioned groups from database.
952 * The static array group is returned, and if it's
953 * called the first time, the <b>Group DAO</b> is used
954 * to get all the groups.
956 * Note: any database errors will be trapped by the DAO.
958 * @param string $groupType
959 * Type of group(Access/Mailing).
960 * @param bool $excludeHidden
961 * Exclude hidden groups.
965 * array reference of all groups.
967 public static function group($groupType = NULL, $excludeHidden = TRUE) {
968 return CRM_Core_Permission
::group($groupType, $excludeHidden);
972 * Fetch groups in a nested format suitable for use in select form element.
973 * @param bool $checkPermissions
974 * @param string|null $groupType
975 * @param bool $excludeHidden
978 public static function nestedGroup($checkPermissions = TRUE, $groupType = NULL, $excludeHidden = TRUE) {
979 $groups = $checkPermissions ? self
::group($groupType, $excludeHidden) : self
::allGroup($groupType, $excludeHidden);
980 return CRM_Contact_BAO_Group
::getGroupsHierarchy($groups, NULL, ' ', TRUE);
984 * Get all permissioned groups from database.
986 * The static array group is returned, and if it's
987 * called the first time, the <b>Group DAO</b> is used
988 * to get all the groups.
990 * Note: any database errors will be trapped by the DAO.
993 * @param bool $onlyPublic
994 * @param null $groupType
995 * @param bool $excludeHidden
998 * array reference of all groups.
1000 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
1001 if (!self
::$staticGroup) {
1002 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
1004 $condition .= " AND visibility != 'User and User Admin Only'";
1008 $condition .= ' AND ' . CRM_Contact_BAO_Group
::groupTypeCondition($groupType);
1011 if ($excludeHidden) {
1012 $condition .= ' AND is_hidden != 1 ';
1015 self
::populate(self
::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
1018 return self
::$staticGroup;
1022 * Get all Relationship Types from database.
1024 * The static array group is returned, and if it's
1025 * called the first time, the <b>RelationshipType DAO</b> is used
1026 * to get all the relationship types.
1028 * Note: any database errors will be trapped by the DAO.
1030 * @param string $valueColumnName
1031 * Db column name/label.
1032 * @param bool $reset
1033 * Reset relationship types if true.
1034 * @param bool|NULL $isActive
1035 * Filter by is_active. NULL to disable.
1038 * array reference of all relationship types.
1040 public static function &relationshipType($valueColumnName = 'label', $reset = FALSE, $isActive = 1) {
1041 $cacheKey = $valueColumnName . '::' . $isActive;
1042 if (!CRM_Utils_Array
::value($cacheKey, self
::$relationshipType) ||
$reset) {
1043 self
::$relationshipType[$cacheKey] = array();
1045 //now we have name/label columns CRM-3336
1046 $column_a_b = "{$valueColumnName}_a_b";
1047 $column_b_a = "{$valueColumnName}_b_a";
1049 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1050 $relationshipTypeDAO->selectAdd();
1051 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1052 if ($isActive !== NULL) {
1053 $relationshipTypeDAO->is_active
= $isActive;
1055 $relationshipTypeDAO->find();
1056 while ($relationshipTypeDAO->fetch()) {
1058 self
::$relationshipType[$cacheKey][$relationshipTypeDAO->id
] = array(
1059 'id' => $relationshipTypeDAO->id
,
1060 $column_a_b => $relationshipTypeDAO->$column_a_b,
1061 $column_b_a => $relationshipTypeDAO->$column_b_a,
1062 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1063 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1064 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1065 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1070 return self
::$relationshipType[$cacheKey];
1074 * Get all the ISO 4217 currency codes
1076 * so far, we use this for validation only, so there's no point of putting this into the database
1080 * array reference of all currency codes
1082 public static function ¤cyCode() {
1083 if (!self
::$currencyCode) {
1084 self
::$currencyCode = array(
1354 return self
::$currencyCode;
1358 * Get all the County from database.
1360 * The static array county is returned, and if it's
1361 * called the first time, the <b>County DAO</b> is used
1362 * to get all the Counties.
1364 * Note: any database errors will be trapped by the DAO.
1367 * @param bool|int $id - Optional id to return
1370 * array reference of all Counties
1372 public static function &county($id = FALSE) {
1373 if (!self
::$county) {
1375 $config = CRM_Core_Config
::singleton();
1376 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1377 self
::populate(self
::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1380 if (array_key_exists($id, self
::$county)) {
1381 return self
::$county[$id];
1384 return CRM_Core_DAO
::$_nullObject;
1387 return self
::$county;
1391 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1392 * Get all active payment processors
1394 * The static array paymentProcessor is returned
1398 * Get payment processors - default is to get only active ones.
1400 * Get test payment processors.
1402 * @param null $additionalCond
1405 * array of all payment processors
1407 public static function paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1408 $condition = "is_test = ";
1409 $condition .= ($test) ?
'1' : '0';
1411 if ($additionalCond) {
1412 $condition .= " AND ( $additionalCond ) ";
1415 // CRM-7178. Make sure we only include payment processors valid in this
1417 $condition .= " AND domain_id = " . CRM_Core_Config
::domainID();
1419 $cacheKey = $condition . '_' . (int) $all;
1420 if (!isset(self
::$paymentProcessor[$cacheKey])) {
1421 self
::populate(self
::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1424 return self
::$paymentProcessor[$cacheKey];
1428 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1430 * The static array paymentProcessorType is returned
1434 * Get payment processors - default is to get only active ones.
1437 * @param string $return
1440 * array of all payment processor types
1442 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1443 $cacheKey = $id . '_' . $return;
1444 if (empty(self
::$paymentProcessorType[$cacheKey])) {
1445 self
::populate(self
::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1447 if ($id && CRM_Utils_Array
::value($id, self
::$paymentProcessorType[$cacheKey])) {
1448 return self
::$paymentProcessorType[$cacheKey][$id];
1450 return self
::$paymentProcessorType[$cacheKey];
1454 * Get all the World Regions from Database.
1460 * array reference of all World Regions
1462 public static function &worldRegion($id = FALSE) {
1463 if (!self
::$worldRegions) {
1464 self
::populate(self
::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1468 if (array_key_exists($id, self
::$worldRegions)) {
1469 return self
::$worldRegions[$id];
1472 return CRM_Core_DAO
::$_nullObject;
1476 return self
::$worldRegions;
1480 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1482 * Get all Activity Statuses.
1484 * The static array activityStatus is returned
1487 * @param string $column
1490 * array reference of all activity statuses
1492 public static function &activityStatus($column = 'label') {
1493 if (NULL === self
::$activityStatus) {
1494 self
::$activityStatus = array();
1496 if (!array_key_exists($column, self
::$activityStatus)) {
1497 self
::$activityStatus[$column] = array();
1499 self
::$activityStatus[$column] = CRM_Core_OptionGroup
::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1502 return self
::$activityStatus[$column];
1506 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1508 * Get all Visibility levels.
1510 * The static array visibility is returned
1513 * @param string $column
1516 * array reference of all Visibility levels.
1518 public static function &visibility($column = 'label') {
1519 if (!isset(self
::$visibility)) {
1520 self
::$visibility = array();
1523 if (!isset(self
::$visibility[$column])) {
1524 self
::$visibility[$column] = CRM_Core_OptionGroup
::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1527 return self
::$visibility[$column];
1531 * @param int $countryID
1532 * @param string $field
1536 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1537 static $_cache = NULL;
1539 $cacheKey = "{$countryID}_{$field}";
1544 if (!empty($_cache[$cacheKey])) {
1545 return $_cache[$cacheKey];
1549 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1550 FROM civicrm_state_province
1551 WHERE country_id = %1
1560 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1563 while ($dao->fetch()) {
1564 $result[$dao->id
] = $dao->name
;
1567 // localise the stateProvince names if in an non-en_US locale
1568 $config = CRM_Core_Config
::singleton();
1570 if ($tsLocale != '' and $tsLocale != 'en_US') {
1571 $i18n = CRM_Core_I18n
::singleton();
1572 $i18n->localizeArray($result, array(
1573 'context' => 'province',
1575 $result = CRM_Utils_Array
::asort($result);
1578 $_cache[$cacheKey] = $result;
1580 CRM_Utils_Hook
::buildStateProvinceForCountry($countryID, $result);
1586 * @param int $stateID
1590 public static function &countyForState($stateID) {
1591 if (is_array($stateID)) {
1592 $states = implode(", ", $stateID);
1594 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1596 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1597 WHERE civicrm_county.state_province_id in ( $states )
1598 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1600 $dao = CRM_Core_DAO
::executeQuery($query);
1603 while ($dao->fetch()) {
1604 $result[$dao->id
] = $dao->abbreviation
. ': ' . $dao->name
;
1609 static $_cache = NULL;
1611 $cacheKey = "{$stateID}_name";
1616 if (!empty($_cache[$cacheKey])) {
1617 return $_cache[$cacheKey];
1621 SELECT civicrm_county.name name, civicrm_county.id id
1623 WHERE state_province_id = %1
1632 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1635 while ($dao->fetch()) {
1636 $result[$dao->id
] = $dao->name
;
1644 * Given a state ID return the country ID, this allows
1645 * us to populate forms and values for downstream code
1647 * @param int $stateID
1650 * the country id that the state belongs to
1652 public static function countryIDForStateID($stateID) {
1653 if (empty($stateID)) {
1654 return CRM_Core_DAO
::$_nullObject;
1659 FROM civicrm_state_province
1662 $params = array(1 => array($stateID, 'Integer'));
1664 return CRM_Core_DAO
::singleValueQuery($query, $params);
1668 * Get all types of Greetings.
1670 * The static array of greeting is returned
1674 * Get All Email Greetings - default is to get only active ones.
1676 * @param string $columnName
1679 * array reference of all greetings.
1681 public static function greeting($filter, $columnName = 'label') {
1682 $index = $filter['greeting_type'] . '_' . $columnName;
1684 // also add contactType to the array
1685 $contactType = CRM_Utils_Array
::value('contact_type', $filter);
1687 $index .= '_' . $contactType;
1690 if (NULL === self
::$greeting) {
1691 self
::$greeting = array();
1694 if (!CRM_Utils_Array
::value($index, self
::$greeting)) {
1695 $filterCondition = NULL;
1697 $filterVal = 'v.filter =';
1698 switch ($contactType) {
1707 case 'Organization':
1711 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1714 self
::$greeting[$index] = CRM_Core_OptionGroup
::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1717 return self
::$greeting[$index];
1721 * Construct array of default greeting values for contact type.
1725 * array reference of default greetings.
1727 public static function &greetingDefaults() {
1728 if (!self
::$greetingDefaults) {
1729 $defaultGreetings = array();
1730 $contactTypes = self
::get('CRM_Contact_DAO_Contact', 'contact_type', array(
1731 'keyColumn' => 'id',
1732 'labelColumn' => 'name',
1735 foreach ($contactTypes as $filter => $contactType) {
1736 $filterCondition = " AND (v.filter = 0 OR v.filter = $filter) AND v.is_default = 1 ";
1738 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1739 $tokenVal = CRM_Core_OptionGroup
::values($greeting, NULL, NULL, NULL, $filterCondition, 'label');
1740 $defaultGreetings[$contactType][$greeting] = $tokenVal;
1744 self
::$greetingDefaults = $defaultGreetings;
1747 return self
::$greetingDefaults;
1751 * Get all extensions.
1753 * The static array extensions
1755 * FIXME: This is called by civix but not by any core code. We
1756 * should provide an API call which civix can use instead.
1760 * array($fullyQualifiedName => $label) list of extensions
1762 public static function &getExtensions() {
1763 if (!self
::$extensions) {
1764 self
::$extensions = array();
1766 SELECT full_name, label
1767 FROM civicrm_extension
1770 $dao = CRM_Core_DAO
::executeQuery($sql);
1771 while ($dao->fetch()) {
1772 self
::$extensions[$dao->full_name
] = $dao->label
;
1776 return self
::$extensions;
1780 * Get all options values.
1782 * The static array option values is returned
1785 * @param bool $optionGroupName
1786 * Get All Option Group values- default is to get only active ones.
1789 * @param null $condition
1792 * array reference of all Option Group Name
1794 public static function accountOptionValues($optionGroupName, $id = NULL, $condition = NULL) {
1795 $cacheKey = $optionGroupName . '_' . $condition;
1796 if (empty(self
::$accountOptionValues[$cacheKey])) {
1797 self
::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup
::values($optionGroupName, FALSE, FALSE, FALSE, $condition);
1800 return CRM_Utils_Array
::value($id, self
::$accountOptionValues[$cacheKey]);
1803 return self
::$accountOptionValues[$cacheKey];
1807 * Fetch the list of active extensions of type 'module'
1809 * @param bool $fresh
1810 * Whether to forcibly reload extensions list from canonical store.
1813 * array(array('prefix' => $, 'file' => $))
1815 public static function getModuleExtensions($fresh = FALSE) {
1816 return CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles($fresh);
1821 * Get all tax rates.
1823 * The static array tax rates is returned
1826 * array list of tax rates with the financial type
1828 public static function getTaxRates() {
1829 if (!isset(Civi
::$statics[__CLASS__
]['taxRates'])) {
1830 Civi
::$statics[__CLASS__
]['taxRates'] = array();
1832 SELECT fa.tax_rate, efa.entity_id
1833 FROM civicrm_entity_financial_account efa
1834 INNER JOIN civicrm_financial_account fa ON fa.id = efa.financial_account_id
1835 INNER JOIN civicrm_option_value cov ON cov.value = efa.account_relationship
1836 INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id
1837 WHERE efa.entity_table = 'civicrm_financial_type'
1838 AND cov.name = 'Sales Tax Account is'
1839 AND cog.name = 'account_relationship'
1840 AND fa.is_active = 1";
1841 $dao = CRM_Core_DAO
::executeQuery($sql);
1842 while ($dao->fetch()) {
1843 Civi
::$statics[__CLASS__
]['taxRates'][$dao->entity_id
] = $dao->tax_rate
;
1847 return Civi
::$statics[__CLASS__
]['taxRates'];