3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
30 * Stores all constants and pseudo constants for CRM application.
32 * examples of constants are "Contact Type" which will always be either
33 * 'Individual', 'Household', 'Organization'.
35 * pseudo constants are entities from the database whose values rarely
36 * change. examples are list of countries, states, location types,
39 * currently we're getting the data from the underlying database. this
40 * will be reworked to use caching.
42 * Note: All pseudoconstants should be uninitialized or default to NULL.
43 * This provides greater consistency/predictability after flushing.
46 * @copyright CiviCRM LLC (c) 2004-2014
50 class CRM_Core_PseudoConstant
{
53 * static cache for pseudoconstant arrays
57 private static $cache;
60 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
66 private static $activityType;
73 private static $stateProvince;
80 private static $county;
83 * states/provinces abbreviations
87 private static $stateProvinceAbbreviation;
94 private static $country;
101 private static $countryIsoCode;
104 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
110 private static $group;
117 private static $groupIterator;
124 private static $relationshipType;
127 * civicrm groups that are not smart groups
131 private static $staticGroup;
138 private static $currencyCode;
145 private static $paymentProcessor;
148 * payment processor types
152 private static $paymentProcessorType;
159 private static $worldRegions;
162 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
168 private static $activityStatus;
175 private static $visibility;
182 private static $greeting;
189 private static $greetingDefaults;
192 * Extensions of type module
196 private static $extensions;
199 * Financial Account Type
203 private static $accountOptionValues;
206 * Low-level option getter, rarely accessed directly.
207 * NOTE: Rather than calling this function directly use CRM_*_BAO_*::buildOptions()
208 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Pseudoconstant+%28option+list%29+Reference
210 * @param String $daoName
211 * @param String $fieldName
212 * @param Array $params
213 * - name string name of the option group
214 * - flip boolean results are return in id => label format if false
215 * if true, the results are reversed
216 * - grouping boolean if true, return the value in 'grouping' column (currently unsupported for tables other than option_value)
217 * - localize boolean if true, localize the results before returning
218 * - condition string|array add condition(s) to the sql query - will be concatenated using 'AND'
219 * - keyColumn string the column to use for 'id'
220 * - labelColumn string the column to use for 'label'
221 * - orderColumn string the column to use for sorting, defaults to 'weight' column if one exists, else defaults to labelColumn
222 * - onlyActive boolean return only the action option values
223 * - fresh boolean ignore cache entries and go back to DB
224 * @param String $context: Context string
226 * @return Array|bool - array on success, FALSE on error.
230 public static function get($daoName, $fieldName, $params = array(), $context = NULL) {
231 CRM_Core_DAO
::buildOptionsContext($context);
232 $flip = !empty($params['flip']);
233 // Merge params with defaults
237 'onlyActive' => ($context == 'validate' ||
$context == 'get') ?
FALSE : TRUE,
241 // Custom fields are not in the schema
242 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
243 $customField = new CRM_Core_DAO_CustomField();
244 $customField->id
= (int) substr($fieldName, 7);
245 $customField->find(TRUE);
248 if (!empty($customField->option_group_id
)) {
249 $options = CRM_Core_OptionGroup
::valuesByID($customField->option_group_id
,
253 // Note: for custom fields the 'name' column is NULL
254 CRM_Utils_Array
::value('labelColumn', $params, 'label'),
255 $params['onlyActive'],
260 if ($customField->data_type
=== 'StateProvince') {
261 $options = self
::stateProvince();
263 elseif ($customField->data_type
=== 'Country') {
264 $options = $context == 'validate' ? self
::countryIsoCode() : self
::country();
266 elseif ($customField->data_type
=== 'Boolean') {
267 $options = $context == 'validate' ?
array(0, 1) : array(1 => ts('Yes'), 0 => ts('No'));
270 CRM_Utils_Hook
::customFieldOptions($customField->id
, $options, FALSE);
271 if ($options && $flip) {
272 $options = array_flip($options);
274 $customField->free();
278 // Core field: load schema
280 $fieldSpec = $dao->getFieldSpec($fieldName);
282 // If neither worked then this field doesn't exist. Return false.
283 if (empty($fieldSpec)) {
287 elseif (!empty($fieldSpec['pseudoconstant'])) {
288 $pseudoconstant = $fieldSpec['pseudoconstant'];
290 // if callback is specified..
291 if(!empty($pseudoconstant['callback'])) {
292 list($className, $fnName) = explode('::', $pseudoconstant['callback']);
293 if (method_exists($className, $fnName)) {
294 return call_user_func(array($className, $fnName));
298 // Merge params with schema defaults
300 'condition' => CRM_Utils_Array
::value('condition', $pseudoconstant, array()),
301 'keyColumn' => CRM_Utils_Array
::value('keyColumn', $pseudoconstant),
302 'labelColumn' => CRM_Utils_Array
::value('labelColumn', $pseudoconstant),
305 // Fetch option group from option_value table
306 if(!empty($pseudoconstant['optionGroupName'])) {
307 if ($context == 'validate') {
308 $params['labelColumn'] = 'name';
310 // Call our generic fn for retrieving from the option_value table
311 return CRM_Core_OptionGroup
::values(
312 $pseudoconstant['optionGroupName'],
316 $params['condition'] ?
' AND ' . implode(' AND ', (array) $params['condition']) : NULL,
317 $params['labelColumn'] ?
$params['labelColumn'] : 'label',
318 $params['onlyActive'],
320 $params['keyColumn'] ?
$params['keyColumn'] : 'value'
324 // Fetch options from other tables
325 if (!empty($pseudoconstant['table'])) {
326 // Normalize params so the serialized cache string will be consistent.
327 CRM_Utils_Array
::remove($params, 'flip', 'fresh');
329 $cacheKey = $daoName . $fieldName . serialize($params);
331 // Retrieve cached options
332 if (isset(self
::$cache[$cacheKey]) && empty($params['fresh'])) {
333 $output = self
::$cache[$cacheKey];
336 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($pseudoconstant['table']);
337 if (!class_exists($daoName)) {
340 // Get list of fields for the option table
342 $availableFields = array_keys($dao->fieldKeys());
345 $select = "SELECT %1 AS id, %2 AS label";
348 $order = "ORDER BY %2";
350 // Use machine name instead of label in validate context
351 if ($context == 'validate') {
352 if (!empty($pseudoconstant['nameColumn'])) {
353 $params['labelColumn'] = $pseudoconstant['nameColumn'];
355 elseif (in_array('name', $availableFields)) {
356 $params['labelColumn'] = '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) 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 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 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|number
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 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 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.
534 * @param array $var the associative array we will fill
535 * @param string $name the name of the DAO
536 * @param boolean $all get all objects. default is to get only active ones.
537 * @param string $retrieve the field that we are interested in (normally name, differs in some objects)
538 * @param string $filter the field that we want to filter the result set with
539 * @param string $condition the condition that gets passed to the final query as the WHERE clause
541 * @param null $orderby
549 public static function populate(
554 $filter = 'is_active',
560 $cacheKey = "CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}";
561 $cache = CRM_Utils_Cache
::singleton();
562 $var = $cache->get($cacheKey);
563 if ($var && empty($force)) {
567 $object = new $name ( );
569 $object->selectAdd();
570 $object->selectAdd("$key, $retrieve");
572 $object->whereAdd($condition);
576 $object->orderBy($retrieve);
579 $object->orderBy($orderby);
583 $object->$filter = 1;
588 while ($object->fetch()) {
589 $var[$object->$key] = $object->$retrieve;
592 $cache->set($cacheKey, $var);
596 * Flush given pseudoconstant so it can be reread from db
597 * nex time it's requested.
602 * @param boolean $name pseudoconstant to be flushed
605 public static function flush($name = 'cache') {
606 if (isset(self
::$
$name)) {
609 if ($name == 'cache') {
610 CRM_Core_OptionGroup
::flushAll();
615 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
617 * Get all Activty types.
619 * The static array activityType is returned
621 * @param boolean $all - get All Activity types - default is to get only active ones.
626 * @return array - array reference of all activity types.
628 public static function &activityType() {
629 $args = func_get_args();
630 $all = CRM_Utils_Array
::value(0, $args, TRUE);
631 $includeCaseActivities = CRM_Utils_Array
::value(1, $args, FALSE);
632 $reset = CRM_Utils_Array
::value(2, $args, FALSE);
633 $returnColumn = CRM_Utils_Array
::value(3, $args, 'label');
634 $includeCampaignActivities = CRM_Utils_Array
::value(4, $args, FALSE);
635 $onlyComponentActivities = CRM_Utils_Array
::value(5, $args, FALSE);
636 $index = (int) $all . '_' . $returnColumn . '_' . (int) $includeCaseActivities;
637 $index .= '_' . (int) $includeCampaignActivities;
638 $index .= '_' . (int) $onlyComponentActivities;
640 if (NULL === self
::$activityType) {
641 self
::$activityType = array();
644 if (!isset(self
::$activityType[$index]) ||
$reset) {
647 $condition = 'AND filter = 0';
649 $componentClause = " v.component_id IS NULL";
650 if ($onlyComponentActivities) {
651 $componentClause = " v.component_id IS NOT NULL";
654 $componentIds = array();
655 $compInfo = CRM_Core_Component
::getEnabledComponents();
657 // build filter for listing activity types only if their
658 // respective components are enabled
659 foreach ($compInfo as $compName => $compObj) {
660 if ($compName == 'CiviCase') {
661 if ($includeCaseActivities) {
662 $componentIds[] = $compObj->componentID
;
665 elseif ($compName == 'CiviCampaign') {
666 if ($includeCampaignActivities) {
667 $componentIds[] = $compObj->componentID
;
671 $componentIds[] = $compObj->componentID
;
675 if (count($componentIds)) {
676 $componentIds = implode(',', $componentIds);
677 $componentClause = " ($componentClause OR v.component_id IN ($componentIds))";
678 if ($onlyComponentActivities) {
679 $componentClause = " ( v.component_id IN ($componentIds ) )";
682 $condition = $condition . ' AND ' . $componentClause;
684 self
::$activityType[$index] = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
686 return self
::$activityType[$index];
690 * Get all the State/Province from database.
692 * The static array stateProvince is returned, and if it's
693 * called the first time, the <b>State Province DAO</b> is used
694 * to get all the States.
696 * Note: any database errors will be trapped by the DAO.
701 * @param int $id - Optional id to return
703 * @return array - array reference of all State/Provinces.
706 public static function &stateProvince($id = FALSE, $limit = TRUE) {
707 if (($id && !CRM_Utils_Array
::value($id, self
::$stateProvince)) ||
!self
::$stateProvince ||
!$id) {
708 $whereClause = FALSE;
709 $config = CRM_Core_Config
::singleton();
711 $countryIsoCodes = self
::countryIsoCode();
712 $limitCodes = $config->provinceLimit();
714 foreach ($limitCodes as $code) {
715 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
717 if (!empty($limitIds)) {
718 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
721 $whereClause = FALSE;
724 self
::populate(self
::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
726 // localise the province names if in an non-en_US locale
728 if ($tsLocale != '' and $tsLocale != 'en_US') {
729 $i18n = CRM_Core_I18n
::singleton();
730 $i18n->localizeArray(self
::$stateProvince, array(
731 'context' => 'province',
733 self
::$stateProvince = CRM_Utils_Array
::asort(self
::$stateProvince);
737 if (array_key_exists($id, self
::$stateProvince)) {
738 return self
::$stateProvince[$id];
745 return self
::$stateProvince;
749 * Get all the State/Province abbreviations from the database.
751 * Same as above, except gets the abbreviations instead of the names.
756 * @param int $id - Optional id to return
758 * @return array - array reference of all State/Province abbreviations.
760 public static function &stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
764 FROM civicrm_state_province
772 return CRM_Core_DAO
::singleValueQuery($query, $params);
775 if (!self
::$stateProvinceAbbreviation ||
!$id) {
777 $whereClause = FALSE;
780 $config = CRM_Core_Config
::singleton();
781 $countryIsoCodes = self
::countryIsoCode();
782 $limitCodes = $config->provinceLimit();
784 foreach ($limitCodes as $code) {
785 $tmpArray = array_keys($countryIsoCodes, $code);
787 if (!empty($tmpArray)) {
788 $limitIds[] = array_shift($tmpArray);
791 if (!empty($limitIds)) {
792 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
795 self
::populate(self
::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
799 if (array_key_exists($id, self
::$stateProvinceAbbreviation)) {
800 return self
::$stateProvinceAbbreviation[$id];
807 return self
::$stateProvinceAbbreviation;
811 * Get all the countries from database.
813 * The static array country is returned, and if it's
814 * called the first time, the <b>Country DAO</b> is used
815 * to get all the countries.
817 * Note: any database errors will be trapped by the DAO.
822 * @param bool|int $id - Optional id to return
824 * @param bool $applyLimit
826 * @return array - array reference of all countries.
828 public static function country($id = FALSE, $applyLimit = TRUE) {
829 if (($id && !CRM_Utils_Array
::value($id, self
::$country)) ||
!self
::$country ||
!$id) {
831 $config = CRM_Core_Config
::singleton();
832 $limitCodes = array();
835 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
836 // (ensuring it's a subset of the legal values)
837 // K/P: We need to fix this, i dont think it works with new setting files
838 $limitCodes = $config->countryLimit();
839 if (!is_array($limitCodes)) {
841 $config->countryLimit
=> 1,
845 $limitCodes = array_intersect(self
::countryIsoCode(), $limitCodes);
848 if (count($limitCodes)) {
849 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
855 self
::populate(self
::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
857 // if default country is set, percolate it to the top
858 if ($config->defaultContactCountry()) {
859 $countryIsoCodes = self
::countryIsoCode();
860 $defaultID = array_search($config->defaultContactCountry(), $countryIsoCodes);
861 if ($defaultID !== FALSE) {
862 $default[$defaultID] = CRM_Utils_Array
::value($defaultID, self
::$country);
863 self
::$country = $default + self
::$country;
867 // localise the country names if in an non-en_US locale
869 if ($tsLocale != '' and $tsLocale != 'en_US') {
870 $i18n = CRM_Core_I18n
::singleton();
871 $i18n->localizeArray(self
::$country, array(
872 'context' => 'country',
874 self
::$country = CRM_Utils_Array
::asort(self
::$country);
878 if (array_key_exists($id, self
::$country)) {
879 return self
::$country[$id];
882 return CRM_Core_DAO
::$_nullObject;
885 return self
::$country;
889 * Get all the country ISO Code abbreviations from the database.
891 * The static array countryIsoCode is returned, and if it's
892 * called the first time, the <b>Country DAO</b> is used
893 * to get all the countries' ISO codes.
895 * Note: any database errors will be trapped by the DAO.
902 * @return array - array reference of all country ISO codes.
904 public static function &countryIsoCode($id = FALSE) {
905 if (!self
::$countryIsoCode) {
906 self
::populate(self
::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
909 if (array_key_exists($id, self
::$countryIsoCode)) {
910 return self
::$countryIsoCode[$id];
913 return CRM_Core_DAO
::$_nullObject;
916 return self
::$countryIsoCode;
920 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
922 * Get all groups from database
924 * The static array group is returned, and if it's
925 * called the first time, the <b>Group DAO</b> is used
926 * to get all the groups.
928 * Note: any database errors will be trapped by the DAO.
930 * @param string $groupType type of group(Access/Mailing)
931 * @param bool|\boolen $excludeHidden exclude hidden groups.
936 * @return array - array reference of all groups.
938 public static function &allGroup($groupType = NULL, $excludeHidden = TRUE) {
939 $condition = CRM_Contact_BAO_Group
::groupTypeCondition($groupType, $excludeHidden);
942 self
::$group = array();
945 $groupKey = $groupType ?
$groupType : 'null';
947 if (!isset(self
::$group[$groupKey])) {
948 self
::$group[$groupKey] = NULL;
949 self
::populate(self
::$group[$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
951 return self
::$group[$groupKey];
955 * Create or get groups iterator (iterates over nested groups in a
958 * The GroupNesting instance is returned; it's created if this is being
959 * called for the first time
965 * @param bool $styledLabels
967 * @return mixed - instance of CRM_Contact_BAO_GroupNesting
969 public static function &groupIterator($styledLabels = FALSE) {
970 if (!self
::$groupIterator) {
972 When used as an object, GroupNesting implements Iterator
973 and iterates nested groups in a logical manner for us
975 self
::$groupIterator = new CRM_Contact_BAO_GroupNesting($styledLabels);
977 return self
::$groupIterator;
981 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
983 * Get all permissioned groups from database
985 * The static array group is returned, and if it's
986 * called the first time, the <b>Group DAO</b> is used
987 * to get all the groups.
989 * Note: any database errors will be trapped by the DAO.
991 * @param string $groupType type of group(Access/Mailing)
992 * @param bool|\boolen $excludeHidden exclude hidden groups.
997 * @return array - array reference of all groups.
999 public static function group($groupType = NULL, $excludeHidden = TRUE) {
1000 return CRM_Core_Permission
::group($groupType, $excludeHidden);
1004 * Get all permissioned groups from database
1006 * The static array group is returned, and if it's
1007 * called the first time, the <b>Group DAO</b> is used
1008 * to get all the groups.
1010 * Note: any database errors will be trapped by the DAO.
1015 * @param bool $onlyPublic
1016 * @param null $groupType
1017 * @param bool $excludeHidden
1019 * @return array - array reference of all groups.
1021 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
1022 if (!self
::$staticGroup) {
1023 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
1025 $condition .= " AND visibility != 'User and User Admin Only'";
1029 $condition .= ' AND ' . CRM_Contact_BAO_Group
::groupTypeCondition($groupType);
1032 if ($excludeHidden) {
1033 $condition .= ' AND is_hidden != 1 ';
1036 self
::populate(self
::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
1039 return self
::$staticGroup;
1043 * Get all Relationship Types from database.
1045 * The static array group is returned, and if it's
1046 * called the first time, the <b>RelationshipType DAO</b> is used
1047 * to get all the relationship types.
1049 * Note: any database errors will be trapped by the DAO.
1051 * @param string $valueColumnName db column name/label.
1052 * @param boolean $reset reset relationship types if true
1057 * @return array - array reference of all relationship types.
1059 public static function &relationshipType($valueColumnName = 'label', $reset = FALSE) {
1060 if (!CRM_Utils_Array
::value($valueColumnName, self
::$relationshipType) ||
$reset) {
1061 self
::$relationshipType[$valueColumnName] = array();
1063 //now we have name/label columns CRM-3336
1064 $column_a_b = "{$valueColumnName}_a_b";
1065 $column_b_a = "{$valueColumnName}_b_a";
1067 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1068 $relationshipTypeDAO->selectAdd();
1069 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1070 $relationshipTypeDAO->is_active
= 1;
1071 $relationshipTypeDAO->find();
1072 while ($relationshipTypeDAO->fetch()) {
1074 self
::$relationshipType[$valueColumnName][$relationshipTypeDAO->id
] = array(
1075 'id' => $relationshipTypeDAO->id
,
1076 $column_a_b => $relationshipTypeDAO->$column_a_b,
1077 $column_b_a => $relationshipTypeDAO->$column_b_a,
1078 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1079 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1080 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1081 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1086 return self
::$relationshipType[$valueColumnName];
1090 * get all the ISO 4217 currency codes
1092 * so far, we use this for validation only, so there's no point of putting this into the database
1096 * @return array - array reference of all currency codes
1099 public static function ¤cyCode() {
1100 if (!self
::$currencyCode) {
1101 self
::$currencyCode = array(
1371 return self
::$currencyCode;
1375 * Get all the County from database.
1377 * The static array county is returned, and if it's
1378 * called the first time, the <b>County DAO</b> is used
1379 * to get all the Counties.
1381 * Note: any database errors will be trapped by the DAO.
1386 * @param bool|int $id - Optional id to return
1388 * @return array - 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
1417 * @param boolean $all - get payment processors - default is to get only active ones.
1418 * @param boolean $test - get test payment processors
1420 * @param null $additionalCond
1422 * @return array - array of all payment processors
1424 public static function &paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1425 $condition = "is_test = ";
1426 $condition .= ($test) ?
'1' : '0';
1428 if ($additionalCond) {
1429 $condition .= " AND ( $additionalCond ) ";
1432 // CRM-7178. Make sure we only include payment processors valid in ths
1434 $condition .= " AND domain_id = " . CRM_Core_Config
::domainID();
1436 $cacheKey = $condition . '_' . (int) $all;
1437 if (!isset(self
::$paymentProcessor[$cacheKey])) {
1438 self
::populate(self
::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1441 return self
::$paymentProcessor[$cacheKey];
1445 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
1447 * The static array paymentProcessorType is returned
1452 * @param boolean $all - get payment processors - default is to get only active ones.
1455 * @param string $return
1457 * @return array - array of all payment processor types
1459 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1460 $cacheKey = $id . '_' .$return;
1461 if (empty(self
::$paymentProcessorType[$cacheKey])) {
1462 self
::populate(self
::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1464 if ($id && CRM_Utils_Array
::value($id, self
::$paymentProcessorType[$cacheKey])) {
1465 return self
::$paymentProcessorType[$cacheKey][$id];
1467 return self
::$paymentProcessorType[$cacheKey];
1471 * Get all the World Regions from Database
1477 * @return array - 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
1507 * @param string $column
1509 * @return array - array reference of all activity statuses
1511 public static function &activityStatus($column = 'label') {
1512 if (NULL === self
::$activityStatus) {
1513 self
::$activityStatus = array();
1515 if (!array_key_exists($column, self
::$activityStatus)) {
1516 self
::$activityStatus[$column] = array();
1518 self
::$activityStatus[$column] = CRM_Core_OptionGroup
::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1521 return self
::$activityStatus[$column];
1525 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
1527 * Get all Visibility levels.
1529 * The static array visibility is returned
1534 * @param string $column
1536 * @return array - array reference of all Visibility levels.
1538 public static function &visibility($column = 'label') {
1539 if (!isset(self
::$visibility)) {
1540 self
::$visibility = array( );
1543 if (!isset(self
::$visibility[$column])) {
1544 self
::$visibility[$column] = CRM_Core_OptionGroup
::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1547 return self
::$visibility[$column];
1550 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1551 static $_cache = NULL;
1553 $cacheKey = "{$countryID}_{$field}";
1558 if (!empty($_cache[$cacheKey])) {
1559 return $_cache[$cacheKey];
1563 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1564 FROM civicrm_state_province
1565 WHERE country_id = %1
1574 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1577 while ($dao->fetch()) {
1578 $result[$dao->id
] = $dao->name
;
1581 // localise the stateProvince names if in an non-en_US locale
1582 $config = CRM_Core_Config
::singleton();
1584 if ($tsLocale != '' and $tsLocale != 'en_US') {
1585 $i18n = CRM_Core_I18n
::singleton();
1586 $i18n->localizeArray($result, array(
1587 'context' => 'province',
1589 $result = CRM_Utils_Array
::asort($result);
1592 $_cache[$cacheKey] = $result;
1594 CRM_Utils_Hook
::buildStateProvinceForCountry($countryID, $result);
1599 public static function &countyForState($stateID) {
1600 if (is_array($stateID)) {
1601 $states = implode(", ", $stateID);
1603 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1605 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1606 WHERE civicrm_county.state_province_id in ( $states )
1607 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1609 $dao = CRM_Core_DAO
::executeQuery($query);
1612 while ($dao->fetch()) {
1613 $result[$dao->id
] = $dao->abbreviation
. ': ' . $dao->name
;
1618 static $_cache = NULL;
1620 $cacheKey = "{$stateID}_name";
1625 if (!empty($_cache[$cacheKey])) {
1626 return $_cache[$cacheKey];
1630 SELECT civicrm_county.name name, civicrm_county.id id
1632 WHERE state_province_id = %1
1641 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1644 while ($dao->fetch()) {
1645 $result[$dao->id
] = $dao->name
;
1653 * Given a state ID return the country ID, this allows
1654 * us to populate forms and values for downstream code
1656 * @param $stateID int
1658 * @return int the country id that the state belongs to
1662 static function countryIDForStateID($stateID) {
1663 if (empty($stateID)) {
1664 return CRM_Core_DAO
::$_nullObject;
1669 FROM civicrm_state_province
1672 $params = array(1 => array($stateID, 'Integer'));
1674 return CRM_Core_DAO
::singleValueQuery($query, $params);
1678 * Get all types of Greetings.
1680 * The static array of greeting is returned
1685 * @param $filter - get All Email Greetings - default is to get only active ones.
1687 * @param string $columnName
1689 * @return array - array reference of all greetings.
1691 public static function greeting($filter, $columnName = 'label') {
1692 $index = $filter['greeting_type'] . '_' . $columnName;
1694 // also add contactType to the array
1695 $contactType = CRM_Utils_Array
::value('contact_type', $filter);
1697 $index .= '_' . $contactType;
1700 if (NULL === self
::$greeting) {
1701 self
::$greeting = array();
1704 if (!CRM_Utils_Array
::value($index, self
::$greeting)) {
1705 $filterCondition = NULL;
1707 $filterVal = 'v.filter =';
1708 switch ($contactType) {
1717 case 'Organization':
1721 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1724 self
::$greeting[$index] = CRM_Core_OptionGroup
::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1727 return self
::$greeting[$index];
1731 * Construct array of default greeting values for contact type
1736 * @return array - array reference of default greetings.
1739 public static function &greetingDefaults() {
1740 if (!self
::$greetingDefaults) {
1741 $defaultGreetings = array();
1742 $contactTypes = self
::get('CRM_Contact_DAO_Contact', 'contact_type', array('keyColumn' => 'id', 'labelColumn' => 'name'));
1744 foreach ($contactTypes as $filter => $contactType) {
1745 $filterCondition = " AND (v.filter = 0 OR v.filter = $filter) AND v.is_default = 1 ";
1747 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1748 $tokenVal = CRM_Core_OptionGroup
::values($greeting, NULL, NULL, NULL, $filterCondition, 'label');
1749 $defaultGreetings[$contactType][$greeting] = $tokenVal;
1753 self
::$greetingDefaults = $defaultGreetings;
1756 return self
::$greetingDefaults;
1760 * Get all extensions
1762 * The static array extensions
1764 * FIXME: This is called by civix but not by any core code. We
1765 * should provide an API call which civix can use instead.
1770 * @return array - array($fullyQualifiedName => $label) list of extensions
1772 public static function &getExtensions() {
1773 if (!self
::$extensions) {
1774 self
::$extensions = array();
1776 SELECT full_name, label
1777 FROM civicrm_extension
1780 $dao = CRM_Core_DAO
::executeQuery($sql);
1781 while ($dao->fetch()) {
1782 self
::$extensions[$dao->full_name
] = $dao->label
;
1786 return self
::$extensions;
1790 * Get all options values
1792 * The static array option values is returned
1797 * @param boolean $optionGroupName - get All Option Group values- default is to get only active ones.
1800 * @param null $condition
1802 * @return array - array reference of all Option Group Name
1804 public static function accountOptionValues($optionGroupName, $id = null, $condition = null) {
1805 $cacheKey = $optionGroupName . '_' . $condition;
1806 if (empty(self
::$accountOptionValues[$cacheKey])) {
1807 self
::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup
::values($optionGroupName, false, false, false, $condition);
1810 return CRM_Utils_Array
::value($id, self
::$accountOptionValues[$cacheKey]);
1813 return self
::$accountOptionValues[$cacheKey];
1817 * Fetch the list of active extensions of type 'module'
1819 * @param $fresh bool whether to forcibly reload extensions list from canonical store
1823 * @return array - array(array('prefix' => $, 'file' => $))
1825 public static function getModuleExtensions($fresh = FALSE) {
1826 return CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles($fresh);