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'
302 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $options, $params);
306 // Fetch options from other tables
307 if (!empty($pseudoconstant['table'])) {
308 // Normalize params so the serialized cache string will be consistent.
309 CRM_Utils_Array
::remove($params, 'flip', 'fresh');
311 $cacheKey = $daoName . $fieldName . serialize($params);
313 // Retrieve cached options
314 if (isset(self
::$cache[$cacheKey]) && empty($params['fresh'])) {
315 $output = self
::$cache[$cacheKey];
318 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($pseudoconstant['table']);
319 if (!class_exists($daoName)) {
322 // Get list of fields for the option table
323 $dao = new $daoName();
324 $availableFields = array_keys($dao->fieldKeys());
327 $select = "SELECT %1 AS id, %2 AS label";
330 $order = "ORDER BY %2";
332 // Use machine name in certain contexts
333 if ($context == 'validate' ||
$context == 'match') {
334 $nameField = $context == 'validate' ?
'labelColumn' : 'keyColumn';
335 if (!empty($pseudoconstant['nameColumn'])) {
336 $params[$nameField] = $pseudoconstant['nameColumn'];
338 elseif (in_array('name', $availableFields)) {
339 $params[$nameField] = 'name';
342 // Condition param can be passed as an sql clause string or an array of clauses
343 if (!empty($params['condition'])) {
344 $wheres[] = implode(' AND ', (array) $params['condition']);
346 // onlyActive param will automatically filter on common flags
347 if (!empty($params['onlyActive'])) {
348 foreach (array('is_active' => 1, 'is_deleted' => 0, 'is_test' => 0, 'is_hidden' => 0) as $flag => $val) {
349 if (in_array($flag, $availableFields)) {
350 $wheres[] = "$flag = $val";
354 // Filter domain specific options
355 if (in_array('domain_id', $availableFields)) {
356 $wheres[] = 'domain_id = ' . CRM_Core_Config
::domainID();
358 $queryParams = array(
359 1 => array($params['keyColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
360 2 => array($params['labelColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
361 3 => array($pseudoconstant['table'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
363 // Add orderColumn param
364 if (!empty($params['orderColumn'])) {
365 $queryParams[4] = array($params['orderColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
);
366 $order = "ORDER BY %4";
368 // Support no sorting if $params[orderColumn] is FALSE
369 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
372 // Default to 'weight' if that column exists
373 elseif (in_array('weight', $availableFields)) {
374 $order = "ORDER BY weight";
378 $query = "$select $from";
380 $query .= " WHERE " . implode($wheres, ' AND ');
382 $query .= ' ' . $order;
383 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
384 while ($dao->fetch()) {
385 $output[$dao->id
] = $dao->label
;
389 if (!empty($params['localize']) ||
$pseudoconstant['table'] == 'civicrm_country' ||
$pseudoconstant['table'] == 'civicrm_state_province') {
390 $I18nParams = array();
391 if ($pseudoconstant['table'] == 'civicrm_country') {
392 $I18nParams['context'] = 'country';
394 if ($pseudoconstant['table'] == 'civicrm_state_province') {
395 $I18nParams['context'] = 'province';
397 $i18n = CRM_Core_I18n
::singleton();
398 $i18n->localizeArray($output, $I18nParams);
399 // Maintain sort by label
400 if ($order == "ORDER BY %2") {
401 CRM_Utils_Array
::asort($output);
404 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $output, $params);
405 self
::$cache[$cacheKey] = $output;
407 return $flip ?
array_flip($output) : $output;
411 // Return "Yes" and "No" for boolean fields
412 elseif (CRM_Utils_Array
::value('type', $fieldSpec) === CRM_Utils_Type
::T_BOOLEAN
) {
413 $output = $context == 'validate' ?
array(0, 1) : CRM_Core_SelectValues
::boolean();
414 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $output, $params);
415 return $flip ?
array_flip($output) : $output;
417 // If we're still here, it's an error. Return FALSE.
422 * Fetch the translated label for a field given its key.
424 * @param string $baoName
425 * @param string $fieldName
426 * @param string|Int $key
428 * TODO: Accept multivalued input?
430 * @return bool|null|string
431 * FALSE if the given field has no associated option list
432 * NULL if the given key has no corresponding option
433 * String if label is found
435 public static function getLabel($baoName, $fieldName, $key) {
436 $values = $baoName::buildOptions($fieldName, 'get');
437 if ($values === FALSE) {
440 return CRM_Utils_Array
::value($key, $values);
444 * Fetch the machine name for a field given its key.
446 * @param string $baoName
447 * @param string $fieldName
448 * @param string|Int $key
450 * @return bool|null|string
451 * FALSE if the given field has no associated option list
452 * NULL if the given key has no corresponding option
453 * String if label is found
455 public static function getName($baoName, $fieldName, $key) {
456 $values = $baoName::buildOptions($fieldName, 'validate');
457 if ($values === FALSE) {
460 return CRM_Utils_Array
::value($key, $values);
464 * Fetch the key for a field option given its name.
466 * @param string $baoName
467 * @param string $fieldName
468 * @param string|Int $value
470 * @return bool|null|string|int
471 * FALSE if the given field has no associated option list
472 * NULL if the given key has no corresponding option
473 * String|Number if key is found
475 public static function getKey($baoName, $fieldName, $value) {
476 $values = $baoName::buildOptions($fieldName, 'validate');
477 if ($values === FALSE) {
480 return CRM_Utils_Array
::key($value, $values);
484 * Lookup the admin page at which a field's option list can be edited
486 * @return string|null
488 public static function getOptionEditUrl($fieldSpec) {
489 // If it's an option group, that's easy
490 if (!empty($fieldSpec['pseudoconstant']['optionGroupName'])) {
491 return 'civicrm/admin/options/' . $fieldSpec['pseudoconstant']['optionGroupName'];
493 // For everything else...
494 elseif (!empty($fieldSpec['pseudoconstant']['table'])) {
495 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($fieldSpec['pseudoconstant']['table']);
499 // We don't have good mapping so have to do a bit of guesswork from the menu
500 list(, $parent, , $child) = explode('_', $daoName);
501 $sql = "SELECT path FROM civicrm_menu
502 WHERE page_callback LIKE '%CRM_Admin_Page_$child%' OR page_callback LIKE '%CRM_{$parent}_Page_$child%'
503 ORDER BY page_callback
505 return CRM_Core_Dao
::singleValueQuery($sql);
511 * DEPRECATED generic populate method.
512 * All pseudoconstant functions that use this method are also @deprecated
514 * The static array $var is populated from the db
515 * using the <b>$name DAO</b>.
517 * Note: any database errors will be trapped by the DAO.
520 * The associative array we will fill.
521 * @param string $name
522 * The name of the DAO.
524 * Get all objects. default is to get only active ones.
525 * @param string $retrieve
526 * The field that we are interested in (normally name, differs in some objects).
527 * @param string $filter
528 * The field that we want to filter the result set with.
529 * @param string $condition
530 * The condition that gets passed to the final query as the WHERE clause.
532 * @param bool $orderby
538 public static function populate(
543 $filter = 'is_active',
549 $cacheKey = "CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}";
550 $cache = CRM_Utils_Cache
::singleton();
551 $var = $cache->get($cacheKey);
552 if ($var && empty($force)) {
556 $object = new $name();
558 $object->selectAdd();
559 $object->selectAdd("$key, $retrieve");
561 $object->whereAdd($condition);
565 $object->orderBy($retrieve);
568 $object->orderBy($orderby);
572 $object->$filter = 1;
577 while ($object->fetch()) {
578 $var[$object->$key] = $object->$retrieve;
581 $cache->set($cacheKey, $var);
585 * Flush given pseudoconstant so it can be reread from db.
586 * nex time it's requested.
589 * @param bool|string $name pseudoconstant to be flushed
591 public static function flush($name = 'cache') {
592 if (isset(self
::$
$name)) {
595 if ($name == 'cache') {
596 CRM_Core_OptionGroup
::flushAll();
601 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
603 * Get all Activty types.
605 * The static array activityType is returned
609 * array reference of all activity types.
611 public static function &activityType() {
612 $args = func_get_args();
613 $all = CRM_Utils_Array
::value(0, $args, TRUE);
614 $includeCaseActivities = CRM_Utils_Array
::value(1, $args, FALSE);
615 $reset = CRM_Utils_Array
::value(2, $args, FALSE);
616 $returnColumn = CRM_Utils_Array
::value(3, $args, 'label');
617 $includeCampaignActivities = CRM_Utils_Array
::value(4, $args, FALSE);
618 $onlyComponentActivities = CRM_Utils_Array
::value(5, $args, FALSE);
619 $index = (int) $all . '_' . $returnColumn . '_' . (int) $includeCaseActivities;
620 $index .= '_' . (int) $includeCampaignActivities;
621 $index .= '_' . (int) $onlyComponentActivities;
623 if (NULL === self
::$activityType) {
624 self
::$activityType = array();
627 if (!isset(self
::$activityType[$index]) ||
$reset) {
630 $condition = 'AND filter = 0';
632 $componentClause = " v.component_id IS NULL";
633 if ($onlyComponentActivities) {
634 $componentClause = " v.component_id IS NOT NULL";
637 $componentIds = array();
638 $compInfo = CRM_Core_Component
::getEnabledComponents();
640 // build filter for listing activity types only if their
641 // respective components are enabled
642 foreach ($compInfo as $compName => $compObj) {
643 if ($compName == 'CiviCase') {
644 if ($includeCaseActivities) {
645 $componentIds[] = $compObj->componentID
;
648 elseif ($compName == 'CiviCampaign') {
649 if ($includeCampaignActivities) {
650 $componentIds[] = $compObj->componentID
;
654 $componentIds[] = $compObj->componentID
;
658 if (count($componentIds)) {
659 $componentIds = implode(',', $componentIds);
660 $componentClause = " ($componentClause OR v.component_id IN ($componentIds))";
661 if ($onlyComponentActivities) {
662 $componentClause = " ( v.component_id IN ($componentIds ) )";
665 $condition = $condition . ' AND ' . $componentClause;
667 self
::$activityType[$index] = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
669 return self
::$activityType[$index];
673 * Get all the State/Province from database.
675 * The static array stateProvince is returned, and if it's
676 * called the first time, the <b>State Province DAO</b> is used
677 * to get all the States.
679 * Note: any database errors will be trapped by the DAO.
682 * @param bool|int $id - Optional id to return
687 * array reference of all State/Provinces.
689 public static function &stateProvince($id = FALSE, $limit = TRUE) {
690 if (($id && !CRM_Utils_Array
::value($id, self
::$stateProvince)) ||
!self
::$stateProvince ||
!$id) {
691 $whereClause = FALSE;
693 $countryIsoCodes = self
::countryIsoCode();
694 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
696 foreach ($limitCodes as $code) {
697 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
699 if (!empty($limitIds)) {
700 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
703 $whereClause = FALSE;
706 self
::populate(self
::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
708 // localise the province names if in an non-en_US locale
710 if ($tsLocale != '' and $tsLocale != 'en_US') {
711 $i18n = CRM_Core_I18n
::singleton();
712 $i18n->localizeArray(self
::$stateProvince, array(
713 'context' => 'province',
715 self
::$stateProvince = CRM_Utils_Array
::asort(self
::$stateProvince);
719 if (array_key_exists($id, self
::$stateProvince)) {
720 return self
::$stateProvince[$id];
727 return self
::$stateProvince;
731 * Get all the State/Province abbreviations from the database.
733 * Same as above, except gets the abbreviations instead of the names.
736 * @param bool|int $id - Optional id to return
741 * array reference of all State/Province abbreviations.
743 public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
744 if ($id && is_numeric($id)) {
745 if (!array_key_exists($id, (array) self
::$stateProvinceAbbreviation)) {
746 $query = "SELECT abbreviation
747 FROM civicrm_state_province
755 self
::$stateProvinceAbbreviation[$id] = CRM_Core_DAO
::singleValueQuery($query, $params);
757 return self
::$stateProvinceAbbreviation[$id];
760 $whereClause = FALSE;
763 $countryIsoCodes = self
::countryIsoCode();
764 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
766 foreach ($limitCodes as $code) {
767 $tmpArray = array_keys($countryIsoCodes, $code);
769 if (!empty($tmpArray)) {
770 $limitIds[] = array_shift($tmpArray);
773 if (!empty($limitIds)) {
774 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
777 self
::populate(self
::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
780 return self
::$stateProvinceAbbreviation;
784 * Get all the countries from database.
786 * The static array country is returned, and if it's
787 * called the first time, the <b>Country DAO</b> is used
788 * to get all the countries.
790 * Note: any database errors will be trapped by the DAO.
793 * @param bool|int $id - Optional id to return
795 * @param bool $applyLimit
798 * array reference of all countries.
800 public static function country($id = FALSE, $applyLimit = TRUE) {
801 if (($id && !CRM_Utils_Array
::value($id, self
::$country)) ||
!self
::$country ||
!$id) {
803 $config = CRM_Core_Config
::singleton();
804 $limitCodes = array();
807 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
808 // (ensuring it's a subset of the legal values)
809 // K/P: We need to fix this, i dont think it works with new setting files
810 $limitCodes = CRM_Core_BAO_Country
::countryLimit();
811 if (!is_array($limitCodes)) {
813 $config->countryLimit
=> 1,
817 $limitCodes = array_intersect(self
::countryIsoCode(), $limitCodes);
820 if (count($limitCodes)) {
821 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
827 self
::populate(self
::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
829 // if default country is set, percolate it to the top
830 if ($config->defaultContactCountry()) {
831 $countryIsoCodes = self
::countryIsoCode();
832 $defaultID = array_search($config->defaultContactCountry(), $countryIsoCodes);
833 if ($defaultID !== FALSE) {
834 $default[$defaultID] = CRM_Utils_Array
::value($defaultID, self
::$country);
835 self
::$country = $default + self
::$country;
839 // localise the country names if in an non-en_US locale
841 if ($tsLocale != '' and $tsLocale != 'en_US') {
842 $i18n = CRM_Core_I18n
::singleton();
843 $i18n->localizeArray(self
::$country, array(
844 'context' => 'country',
846 self
::$country = CRM_Utils_Array
::asort(self
::$country);
850 if (array_key_exists($id, self
::$country)) {
851 return self
::$country[$id];
854 return CRM_Core_DAO
::$_nullObject;
857 return self
::$country;
861 * Get all the country ISO Code abbreviations from the database.
863 * The static array countryIsoCode is returned, and if it's
864 * called the first time, the <b>Country DAO</b> is used
865 * to get all the countries' ISO codes.
867 * Note: any database errors will be trapped by the DAO.
873 * array reference of all country ISO codes.
875 public static function &countryIsoCode($id = FALSE) {
876 if (!self
::$countryIsoCode) {
877 self
::populate(self
::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
880 if (array_key_exists($id, self
::$countryIsoCode)) {
881 return self
::$countryIsoCode[$id];
884 return CRM_Core_DAO
::$_nullObject;
887 return self
::$countryIsoCode;
891 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
893 * Get all groups from database
895 * The static array group is returned, and if it's
896 * called the first time, the <b>Group DAO</b> is used
897 * to get all the groups.
899 * Note: any database errors will be trapped by the DAO.
901 * @param string $groupType
902 * Type of group(Access/Mailing).
903 * @param bool $excludeHidden
904 * Exclude hidden groups.
908 * array reference of all groups.
910 public static function allGroup($groupType = NULL, $excludeHidden = TRUE) {
911 $condition = CRM_Contact_BAO_Group
::groupTypeCondition($groupType, $excludeHidden);
914 self
::$group = array();
917 $groupKey = ($groupType ?
$groupType : 'null') . !empty($excludeHidden);
919 if (!isset(self
::$group[$groupKey])) {
920 self
::$group[$groupKey] = NULL;
921 self
::populate(self
::$group[$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
923 return self
::$group[$groupKey];
927 * Create or get groups iterator (iterates over nested groups in a
930 * The GroupNesting instance is returned; it's created if this is being
931 * called for the first time
935 * @param bool $styledLabels
937 * @return CRM_Contact_BAO_GroupNesting
939 public static function &groupIterator($styledLabels = FALSE) {
940 if (!self
::$groupIterator) {
941 // When used as an object, GroupNesting implements Iterator
942 // and iterates nested groups in a logical manner for us
943 self
::$groupIterator = new CRM_Contact_BAO_GroupNesting($styledLabels);
945 return self
::$groupIterator;
949 * Get all permissioned groups from database.
951 * The static array group is returned, and if it's
952 * called the first time, the <b>Group DAO</b> is used
953 * to get all the groups.
955 * Note: any database errors will be trapped by the DAO.
957 * @param string $groupType
958 * Type of group(Access/Mailing).
959 * @param bool $excludeHidden
960 * Exclude hidden groups.
964 * array reference of all groups.
966 public static function group($groupType = NULL, $excludeHidden = TRUE) {
967 return CRM_Core_Permission
::group($groupType, $excludeHidden);
971 * Fetch groups in a nested format suitable for use in select form element.
972 * @param bool $checkPermissions
973 * @param string|null $groupType
974 * @param bool $excludeHidden
977 public static function nestedGroup($checkPermissions = TRUE, $groupType = NULL, $excludeHidden = TRUE) {
978 $groups = $checkPermissions ? self
::group($groupType, $excludeHidden) : self
::allGroup($groupType, $excludeHidden);
979 return CRM_Contact_BAO_Group
::getGroupsHierarchy($groups, NULL, ' ', TRUE);
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.
992 * @param bool $onlyPublic
993 * @param null $groupType
994 * @param bool $excludeHidden
997 * array reference of all groups.
999 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
1000 if (!self
::$staticGroup) {
1001 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
1003 $condition .= " AND visibility != 'User and User Admin Only'";
1007 $condition .= ' AND ' . CRM_Contact_BAO_Group
::groupTypeCondition($groupType);
1010 if ($excludeHidden) {
1011 $condition .= ' AND is_hidden != 1 ';
1014 self
::populate(self
::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
1017 return self
::$staticGroup;
1021 * Get all Relationship Types from database.
1023 * The static array group is returned, and if it's
1024 * called the first time, the <b>RelationshipType DAO</b> is used
1025 * to get all the relationship types.
1027 * Note: any database errors will be trapped by the DAO.
1029 * @param string $valueColumnName
1030 * Db column name/label.
1031 * @param bool $reset
1032 * Reset relationship types if true.
1033 * @param bool|NULL $isActive
1034 * Filter by is_active. NULL to disable.
1037 * array reference of all relationship types.
1039 public static function &relationshipType($valueColumnName = 'label', $reset = FALSE, $isActive = 1) {
1040 $cacheKey = $valueColumnName . '::' . $isActive;
1041 if (!CRM_Utils_Array
::value($cacheKey, self
::$relationshipType) ||
$reset) {
1042 self
::$relationshipType[$cacheKey] = array();
1044 //now we have name/label columns CRM-3336
1045 $column_a_b = "{$valueColumnName}_a_b";
1046 $column_b_a = "{$valueColumnName}_b_a";
1048 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1049 $relationshipTypeDAO->selectAdd();
1050 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1051 if ($isActive !== NULL) {
1052 $relationshipTypeDAO->is_active
= $isActive;
1054 $relationshipTypeDAO->find();
1055 while ($relationshipTypeDAO->fetch()) {
1057 self
::$relationshipType[$cacheKey][$relationshipTypeDAO->id
] = array(
1058 'id' => $relationshipTypeDAO->id
,
1059 $column_a_b => $relationshipTypeDAO->$column_a_b,
1060 $column_b_a => $relationshipTypeDAO->$column_b_a,
1061 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1062 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1063 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1064 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1069 return self
::$relationshipType[$cacheKey];
1073 * Get all the ISO 4217 currency codes
1075 * so far, we use this for validation only, so there's no point of putting this into the database
1079 * array reference of all currency codes
1081 public static function ¤cyCode() {
1082 if (!self
::$currencyCode) {
1083 self
::$currencyCode = array(
1353 return self
::$currencyCode;
1357 * Get all the County from database.
1359 * The static array county is returned, and if it's
1360 * called the first time, the <b>County DAO</b> is used
1361 * to get all the Counties.
1363 * Note: any database errors will be trapped by the DAO.
1366 * @param bool|int $id - Optional id to return
1369 * array reference of all Counties
1371 public static function &county($id = FALSE) {
1372 if (!self
::$county) {
1374 $config = CRM_Core_Config
::singleton();
1375 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1376 self
::populate(self
::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1379 if (array_key_exists($id, self
::$county)) {
1380 return self
::$county[$id];
1383 return CRM_Core_DAO
::$_nullObject;
1386 return self
::$county;
1390 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1391 * Get all active payment processors
1393 * The static array paymentProcessor is returned
1397 * Get payment processors - default is to get only active ones.
1399 * Get test payment processors.
1401 * @param null $additionalCond
1404 * array of all payment processors
1406 public static function paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1407 $condition = "is_test = ";
1408 $condition .= ($test) ?
'1' : '0';
1410 if ($additionalCond) {
1411 $condition .= " AND ( $additionalCond ) ";
1414 // CRM-7178. Make sure we only include payment processors valid in this
1416 $condition .= " AND domain_id = " . CRM_Core_Config
::domainID();
1418 $cacheKey = $condition . '_' . (int) $all;
1419 if (!isset(self
::$paymentProcessor[$cacheKey])) {
1420 self
::populate(self
::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1423 return self
::$paymentProcessor[$cacheKey];
1427 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1429 * The static array paymentProcessorType is returned
1433 * Get payment processors - default is to get only active ones.
1436 * @param string $return
1439 * array of all payment processor types
1441 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1442 $cacheKey = $id . '_' . $return;
1443 if (empty(self
::$paymentProcessorType[$cacheKey])) {
1444 self
::populate(self
::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1446 if ($id && CRM_Utils_Array
::value($id, self
::$paymentProcessorType[$cacheKey])) {
1447 return self
::$paymentProcessorType[$cacheKey][$id];
1449 return self
::$paymentProcessorType[$cacheKey];
1453 * Get all the World Regions from Database.
1459 * array reference of all World Regions
1461 public static function &worldRegion($id = FALSE) {
1462 if (!self
::$worldRegions) {
1463 self
::populate(self
::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1467 if (array_key_exists($id, self
::$worldRegions)) {
1468 return self
::$worldRegions[$id];
1471 return CRM_Core_DAO
::$_nullObject;
1475 return self
::$worldRegions;
1479 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1481 * Get all Activity Statuses.
1483 * The static array activityStatus is returned
1486 * @param string $column
1489 * array reference of all activity statuses
1491 public static function &activityStatus($column = 'label') {
1492 if (NULL === self
::$activityStatus) {
1493 self
::$activityStatus = array();
1495 if (!array_key_exists($column, self
::$activityStatus)) {
1496 self
::$activityStatus[$column] = array();
1498 self
::$activityStatus[$column] = CRM_Core_OptionGroup
::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1501 return self
::$activityStatus[$column];
1505 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1507 * Get all Visibility levels.
1509 * The static array visibility is returned
1512 * @param string $column
1515 * array reference of all Visibility levels.
1517 public static function &visibility($column = 'label') {
1518 if (!isset(self
::$visibility)) {
1519 self
::$visibility = array();
1522 if (!isset(self
::$visibility[$column])) {
1523 self
::$visibility[$column] = CRM_Core_OptionGroup
::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1526 return self
::$visibility[$column];
1530 * @param int $countryID
1531 * @param string $field
1535 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1536 static $_cache = NULL;
1538 $cacheKey = "{$countryID}_{$field}";
1543 if (!empty($_cache[$cacheKey])) {
1544 return $_cache[$cacheKey];
1548 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1549 FROM civicrm_state_province
1550 WHERE country_id = %1
1559 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1562 while ($dao->fetch()) {
1563 $result[$dao->id
] = $dao->name
;
1566 // localise the stateProvince names if in an non-en_US locale
1567 $config = CRM_Core_Config
::singleton();
1569 if ($tsLocale != '' and $tsLocale != 'en_US') {
1570 $i18n = CRM_Core_I18n
::singleton();
1571 $i18n->localizeArray($result, array(
1572 'context' => 'province',
1574 $result = CRM_Utils_Array
::asort($result);
1577 $_cache[$cacheKey] = $result;
1579 CRM_Utils_Hook
::buildStateProvinceForCountry($countryID, $result);
1585 * @param int $stateID
1589 public static function &countyForState($stateID) {
1590 if (is_array($stateID)) {
1591 $states = implode(", ", $stateID);
1593 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1595 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1596 WHERE civicrm_county.state_province_id in ( $states )
1597 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1599 $dao = CRM_Core_DAO
::executeQuery($query);
1602 while ($dao->fetch()) {
1603 $result[$dao->id
] = $dao->abbreviation
. ': ' . $dao->name
;
1608 static $_cache = NULL;
1610 $cacheKey = "{$stateID}_name";
1615 if (!empty($_cache[$cacheKey])) {
1616 return $_cache[$cacheKey];
1620 SELECT civicrm_county.name name, civicrm_county.id id
1622 WHERE state_province_id = %1
1631 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1634 while ($dao->fetch()) {
1635 $result[$dao->id
] = $dao->name
;
1643 * Given a state ID return the country ID, this allows
1644 * us to populate forms and values for downstream code
1646 * @param int $stateID
1649 * the country id that the state belongs to
1651 public static function countryIDForStateID($stateID) {
1652 if (empty($stateID)) {
1653 return CRM_Core_DAO
::$_nullObject;
1658 FROM civicrm_state_province
1661 $params = array(1 => array($stateID, 'Integer'));
1663 return CRM_Core_DAO
::singleValueQuery($query, $params);
1667 * Get all types of Greetings.
1669 * The static array of greeting is returned
1673 * Get All Email Greetings - default is to get only active ones.
1675 * @param string $columnName
1678 * array reference of all greetings.
1680 public static function greeting($filter, $columnName = 'label') {
1681 $index = $filter['greeting_type'] . '_' . $columnName;
1683 // also add contactType to the array
1684 $contactType = CRM_Utils_Array
::value('contact_type', $filter);
1686 $index .= '_' . $contactType;
1689 if (NULL === self
::$greeting) {
1690 self
::$greeting = array();
1693 if (!CRM_Utils_Array
::value($index, self
::$greeting)) {
1694 $filterCondition = NULL;
1696 $filterVal = 'v.filter =';
1697 switch ($contactType) {
1706 case 'Organization':
1710 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1713 self
::$greeting[$index] = CRM_Core_OptionGroup
::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1716 return self
::$greeting[$index];
1720 * Construct array of default greeting values for contact type.
1724 * array reference of default greetings.
1726 public static function &greetingDefaults() {
1727 if (!self
::$greetingDefaults) {
1728 $defaultGreetings = array();
1729 $contactTypes = self
::get('CRM_Contact_DAO_Contact', 'contact_type', array(
1730 'keyColumn' => 'id',
1731 'labelColumn' => 'name',
1734 foreach ($contactTypes as $filter => $contactType) {
1735 $filterCondition = " AND (v.filter = 0 OR v.filter = $filter) AND v.is_default = 1 ";
1737 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1738 $tokenVal = CRM_Core_OptionGroup
::values($greeting, NULL, NULL, NULL, $filterCondition, 'label');
1739 $defaultGreetings[$contactType][$greeting] = $tokenVal;
1743 self
::$greetingDefaults = $defaultGreetings;
1746 return self
::$greetingDefaults;
1750 * Get all extensions.
1752 * The static array extensions
1754 * FIXME: This is called by civix but not by any core code. We
1755 * should provide an API call which civix can use instead.
1759 * array($fullyQualifiedName => $label) list of extensions
1761 public static function &getExtensions() {
1762 if (!self
::$extensions) {
1763 self
::$extensions = array();
1765 SELECT full_name, label
1766 FROM civicrm_extension
1769 $dao = CRM_Core_DAO
::executeQuery($sql);
1770 while ($dao->fetch()) {
1771 self
::$extensions[$dao->full_name
] = $dao->label
;
1775 return self
::$extensions;
1779 * Get all options values.
1781 * The static array option values is returned
1784 * @param bool $optionGroupName
1785 * Get All Option Group values- default is to get only active ones.
1788 * @param null $condition
1791 * array reference of all Option Group Name
1793 public static function accountOptionValues($optionGroupName, $id = NULL, $condition = NULL) {
1794 $cacheKey = $optionGroupName . '_' . $condition;
1795 if (empty(self
::$accountOptionValues[$cacheKey])) {
1796 self
::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup
::values($optionGroupName, FALSE, FALSE, FALSE, $condition);
1799 return CRM_Utils_Array
::value($id, self
::$accountOptionValues[$cacheKey]);
1802 return self
::$accountOptionValues[$cacheKey];
1806 * Fetch the list of active extensions of type 'module'
1808 * @param bool $fresh
1809 * Whether to forcibly reload extensions list from canonical store.
1812 * array(array('prefix' => $, 'file' => $))
1814 public static function getModuleExtensions($fresh = FALSE) {
1815 return CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles($fresh);
1820 * Get all tax rates.
1822 * The static array tax rates is returned
1825 * array list of tax rates with the financial type
1827 public static function getTaxRates() {
1828 if (!isset(Civi
::$statics[__CLASS__
]['taxRates'])) {
1829 Civi
::$statics[__CLASS__
]['taxRates'] = array();
1831 SELECT fa.tax_rate, efa.entity_id
1832 FROM civicrm_entity_financial_account efa
1833 INNER JOIN civicrm_financial_account fa ON fa.id = efa.financial_account_id
1834 INNER JOIN civicrm_option_value cov ON cov.value = efa.account_relationship
1835 INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id
1836 WHERE efa.entity_table = 'civicrm_financial_type'
1837 AND cov.name = 'Sales Tax Account is'
1838 AND cog.name = 'account_relationship'
1839 AND fa.is_active = 1";
1840 $dao = CRM_Core_DAO
::executeQuery($sql);
1841 while ($dao->fetch()) {
1842 Civi
::$statics[__CLASS__
]['taxRates'][$dao->entity_id
] = $dao->tax_rate
;
1846 return Civi
::$statics[__CLASS__
]['taxRates'];