3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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 $relationshipType;
109 * Civicrm groups that are not smart groups
112 private static $staticGroup;
118 private static $currencyCode;
124 private static $paymentProcessor;
127 * Payment processor types
130 private static $paymentProcessorType;
136 private static $worldRegions;
139 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
144 private static $activityStatus;
150 private static $visibility;
156 private static $greeting;
162 private static $greetingDefaults;
165 * Extensions of type module
168 private static $extensions;
171 * Financial Account Type
174 private static $accountOptionValues;
177 * Low-level option getter, rarely accessed directly.
178 * NOTE: Rather than calling this function directly use CRM_*_BAO_*::buildOptions()
179 * @see http://wiki.civicrm.org/confluence/display/CRMDOC/Pseudoconstant+%28option+list%29+Reference
181 * NOTE: If someone undertakes a refactoring of this, please consider the use-case of
182 * the Setting.getoptions API. There is no DAO/field, but it would be nice to use the
183 * same 'pseudoconstant' struct in *.settings.php. This means loosening the coupling
184 * between $field lookup and the $pseudoconstant evaluation.
186 * @param string $daoName
187 * @param string $fieldName
188 * @param array $params
189 * - name string name of the option group
190 * - flip boolean results are return in id => label format if false
191 * if true, the results are reversed
192 * - grouping boolean if true, return the value in 'grouping' column (currently unsupported for tables other than option_value)
193 * - localize boolean if true, localize the results before returning
194 * - condition string|array add condition(s) to the sql query - will be concatenated using 'AND'
195 * - keyColumn string the column to use for 'id'
196 * - labelColumn string the column to use for 'label'
197 * - orderColumn string the column to use for sorting, defaults to 'weight' column if one exists, else defaults to labelColumn
198 * - onlyActive boolean return only the action option values
199 * - fresh boolean ignore cache entries and go back to DB
200 * @param string $context : Context string
203 * array on success, FALSE on error.
206 public static function get($daoName, $fieldName, $params = array(), $context = NULL) {
207 CRM_Core_DAO
::buildOptionsContext($context);
208 $flip = !empty($params['flip']);
209 // Merge params with defaults
213 'onlyActive' => ($context == 'validate' ||
$context == 'get') ?
FALSE : TRUE,
215 'context' => $context,
217 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getCanonicalClassName($daoName));
219 // Custom fields are not in the schema
220 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
221 $customField = new CRM_Core_BAO_CustomField();
222 $customField->id
= (int) substr($fieldName, 7);
223 $options = $customField->getOptions($context);
224 if ($options && $flip) {
225 $options = array_flip($options);
227 $customField->free();
231 // Core field: load schema
232 $dao = new $daoName();
233 $fieldSpec = $dao->getFieldSpec($fieldName);
236 // Ensure we have the canonical name for this field
237 $fieldName = CRM_Utils_Array
::value('name', $fieldSpec, $fieldName);
239 // Return false if field doesn't exist.
240 if (empty($fieldSpec)) {
244 elseif (!empty($fieldSpec['pseudoconstant'])) {
245 $pseudoconstant = $fieldSpec['pseudoconstant'];
247 // if callback is specified..
248 if (!empty($pseudoconstant['callback'])) {
249 $fieldOptions = call_user_func(Civi\Core\Resolver
::singleton()->get($pseudoconstant['callback']), $context);
250 //CRM-18223: Allow additions to field options via hook.
251 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $fieldOptions, $params);
252 return $fieldOptions;
255 // Merge params with schema defaults
257 'condition' => CRM_Utils_Array
::value('condition', $pseudoconstant, array()),
258 'keyColumn' => CRM_Utils_Array
::value('keyColumn', $pseudoconstant),
259 'labelColumn' => CRM_Utils_Array
::value('labelColumn', $pseudoconstant),
262 if ($context == 'abbreviate') {
263 switch ($fieldName) {
264 case 'state_province_id':
265 $params['labelColumn'] = 'abbreviation';
269 $params['labelColumn'] = 'iso_code';
276 // Fetch option group from option_value table
277 if (!empty($pseudoconstant['optionGroupName'])) {
278 if ($context == 'validate') {
279 $params['labelColumn'] = 'name';
281 if ($context == 'match') {
282 $params['keyColumn'] = 'name';
284 // Call our generic fn for retrieving from the option_value table
285 $options = CRM_Core_OptionGroup
::values(
286 $pseudoconstant['optionGroupName'],
290 $params['condition'] ?
' AND ' . implode(' AND ', (array) $params['condition']) : NULL,
291 $params['labelColumn'] ?
$params['labelColumn'] : 'label',
292 $params['onlyActive'],
294 $params['keyColumn'] ?
$params['keyColumn'] : 'value',
295 !empty($params['orderColumn']) ?
$params['orderColumn'] : 'weight'
297 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $options, $params);
301 // Fetch options from other tables
302 if (!empty($pseudoconstant['table'])) {
303 // Normalize params so the serialized cache string will be consistent.
304 CRM_Utils_Array
::remove($params, 'flip', 'fresh');
306 $cacheKey = $daoName . $fieldName . serialize($params);
308 // Retrieve cached options
309 if (isset(self
::$cache[$cacheKey]) && empty($params['fresh'])) {
310 $output = self
::$cache[$cacheKey];
313 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($pseudoconstant['table']);
314 if (!class_exists($daoName)) {
317 // Get list of fields for the option table
318 $dao = new $daoName();
319 $availableFields = array_keys($dao->fieldKeys());
322 $select = "SELECT %1 AS id, %2 AS label";
325 $order = "ORDER BY %2";
327 // Use machine name in certain contexts
328 if ($context == 'validate' ||
$context == 'match') {
329 $nameField = $context == 'validate' ?
'labelColumn' : 'keyColumn';
330 if (!empty($pseudoconstant['nameColumn'])) {
331 $params[$nameField] = $pseudoconstant['nameColumn'];
333 elseif (in_array('name', $availableFields)) {
334 $params[$nameField] = 'name';
337 // Condition param can be passed as an sql clause string or an array of clauses
338 if (!empty($params['condition'])) {
339 $wheres[] = implode(' AND ', (array) $params['condition']);
341 // onlyActive param will automatically filter on common flags
342 if (!empty($params['onlyActive'])) {
343 foreach (array('is_active' => 1, 'is_deleted' => 0, 'is_test' => 0, 'is_hidden' => 0) as $flag => $val) {
344 if (in_array($flag, $availableFields)) {
345 $wheres[] = "$flag = $val";
349 // Filter domain specific options
350 if (in_array('domain_id', $availableFields)) {
351 $wheres[] = 'domain_id = ' . CRM_Core_Config
::domainID();
353 $queryParams = array(
354 1 => array($params['keyColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
355 2 => array($params['labelColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
356 3 => array($pseudoconstant['table'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
358 // Add orderColumn param
359 if (!empty($params['orderColumn'])) {
360 $queryParams[4] = array($params['orderColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
);
361 $order = "ORDER BY %4";
363 // Support no sorting if $params[orderColumn] is FALSE
364 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
367 // Default to 'weight' if that column exists
368 elseif (in_array('weight', $availableFields)) {
369 $order = "ORDER BY weight";
373 $query = "$select $from";
375 $query .= " WHERE " . implode($wheres, ' AND ');
377 $query .= ' ' . $order;
378 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
379 while ($dao->fetch()) {
380 $output[$dao->id
] = $dao->label
;
384 if (!empty($params['localize']) ||
$pseudoconstant['table'] == 'civicrm_country' ||
$pseudoconstant['table'] == 'civicrm_state_province') {
385 $I18nParams = array();
386 if ($pseudoconstant['table'] == 'civicrm_country') {
387 $I18nParams['context'] = 'country';
389 if ($pseudoconstant['table'] == 'civicrm_state_province') {
390 $I18nParams['context'] = 'province';
392 $i18n = CRM_Core_I18n
::singleton();
393 $i18n->localizeArray($output, $I18nParams);
394 // Maintain sort by label
395 if ($order == "ORDER BY %2") {
396 CRM_Utils_Array
::asort($output);
399 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $output, $params);
400 self
::$cache[$cacheKey] = $output;
402 return $flip ?
array_flip($output) : $output;
406 // Return "Yes" and "No" for boolean fields
407 elseif (CRM_Utils_Array
::value('type', $fieldSpec) === CRM_Utils_Type
::T_BOOLEAN
) {
408 $output = $context == 'validate' ?
array(0, 1) : CRM_Core_SelectValues
::boolean();
409 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $output, $params);
410 return $flip ?
array_flip($output) : $output;
412 // If we're still here, it's an error. Return FALSE.
417 * Fetch the translated label for a field given its key.
419 * @param string $baoName
420 * @param string $fieldName
421 * @param string|Int $key
423 * TODO: Accept multivalued input?
425 * @return bool|null|string
426 * FALSE if the given field has no associated option list
427 * NULL if the given key has no corresponding option
428 * String if label is found
430 public static function getLabel($baoName, $fieldName, $key) {
431 $values = $baoName::buildOptions($fieldName, 'get');
432 if ($values === FALSE) {
435 return CRM_Utils_Array
::value($key, $values);
439 * Fetch the machine name for a field given its key.
441 * @param string $baoName
442 * @param string $fieldName
443 * @param string|Int $key
445 * @return bool|null|string
446 * FALSE if the given field has no associated option list
447 * NULL if the given key has no corresponding option
448 * String if label is found
450 public static function getName($baoName, $fieldName, $key) {
451 $values = $baoName::buildOptions($fieldName, 'validate');
452 if ($values === FALSE) {
455 return CRM_Utils_Array
::value($key, $values);
459 * Fetch the key for a field option given its name.
461 * @param string $baoName
462 * @param string $fieldName
463 * @param string|Int $value
465 * @return bool|null|string|int
466 * FALSE if the given field has no associated option list
467 * NULL if the given key has no corresponding option
468 * String|Number if key is found
470 public static function getKey($baoName, $fieldName, $value) {
471 $values = $baoName::buildOptions($fieldName, 'validate');
472 if ($values === FALSE) {
475 return CRM_Utils_Array
::key($value, $values);
479 * Lookup the admin page at which a field's option list can be edited
481 * @return string|null
483 public static function getOptionEditUrl($fieldSpec) {
484 // If it's an option group, that's easy
485 if (!empty($fieldSpec['pseudoconstant']['optionGroupName'])) {
486 return 'civicrm/admin/options/' . $fieldSpec['pseudoconstant']['optionGroupName'];
488 // For everything else...
489 elseif (!empty($fieldSpec['pseudoconstant']['table'])) {
490 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($fieldSpec['pseudoconstant']['table']);
494 // We don't have good mapping so have to do a bit of guesswork from the menu
495 list(, $parent, , $child) = explode('_', $daoName);
496 $sql = "SELECT path FROM civicrm_menu
497 WHERE page_callback LIKE '%CRM_Admin_Page_$child%' OR page_callback LIKE '%CRM_{$parent}_Page_$child%'
498 ORDER BY page_callback
500 return CRM_Core_Dao
::singleValueQuery($sql);
506 * DEPRECATED generic populate method.
507 * All pseudoconstant functions that use this method are also @deprecated
509 * The static array $var is populated from the db
510 * using the <b>$name DAO</b>.
512 * Note: any database errors will be trapped by the DAO.
515 * The associative array we will fill.
516 * @param string $name
517 * The name of the DAO.
519 * Get all objects. default is to get only active ones.
520 * @param string $retrieve
521 * The field that we are interested in (normally name, differs in some objects).
522 * @param string $filter
523 * The field that we want to filter the result set with.
524 * @param string $condition
525 * The condition that gets passed to the final query as the WHERE clause.
527 * @param bool $orderby
533 public static function populate(
538 $filter = 'is_active',
544 $cacheKey = "CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}";
545 $cache = CRM_Utils_Cache
::singleton();
546 $var = $cache->get($cacheKey);
547 if ($var && empty($force)) {
551 /* @var CRM_Core_DAO $object */
552 $object = new $name();
554 $object->selectAdd();
555 $object->selectAdd("$key, $retrieve");
557 $object->whereAdd($condition);
561 $object->orderBy($retrieve);
564 $object->orderBy($orderby);
568 $object->$filter = 1;
569 $aclClauses = array_filter($name::getSelectWhereClause());
570 foreach ($aclClauses as $clause) {
571 $object->whereAdd($clause);
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
709 $tsLocale = CRM_Core_I18n
::getLocale();
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
840 $tsLocale = CRM_Core_I18n
::getLocale();
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];
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);
912 $groupKey = ($groupType ?
$groupType : 'null') . !empty($excludeHidden);
914 if (!isset(Civi
::$statics[__CLASS__
]['groups']['allGroup'][$groupKey])) {
915 self
::populate(Civi
::$statics[__CLASS__
]['groups']['allGroup'][$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
917 return Civi
::$statics[__CLASS__
]['groups']['allGroup'][$groupKey];
921 * Get all permissioned groups from database.
923 * The static array group is returned, and if it's
924 * called the first time, the <b>Group DAO</b> is used
925 * to get all the groups.
927 * Note: any database errors will be trapped by the DAO.
929 * @param string $groupType
930 * Type of group(Access/Mailing).
931 * @param bool $excludeHidden
932 * Exclude hidden groups.
936 * array reference of all groups.
938 public static function group($groupType = NULL, $excludeHidden = TRUE) {
939 return CRM_Core_Permission
::group($groupType, $excludeHidden);
943 * Fetch groups in a nested format suitable for use in select form element.
944 * @param bool $checkPermissions
945 * @param string|null $groupType
946 * @param bool $excludeHidden
949 public static function nestedGroup($checkPermissions = TRUE, $groupType = NULL, $excludeHidden = TRUE) {
950 $groups = $checkPermissions ? self
::group($groupType, $excludeHidden) : self
::allGroup($groupType, $excludeHidden);
951 return CRM_Contact_BAO_Group
::getGroupsHierarchy($groups, NULL, ' ', TRUE);
955 * Get all permissioned groups from database.
957 * The static array group is returned, and if it's
958 * called the first time, the <b>Group DAO</b> is used
959 * to get all the groups.
961 * Note: any database errors will be trapped by the DAO.
964 * @param bool $onlyPublic
965 * @param null $groupType
966 * @param bool $excludeHidden
969 * array reference of all groups.
971 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
972 if (!self
::$staticGroup) {
973 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
975 $condition .= " AND visibility != 'User and User Admin Only'";
979 $condition .= ' AND ' . CRM_Contact_BAO_Group
::groupTypeCondition($groupType);
982 if ($excludeHidden) {
983 $condition .= ' AND is_hidden != 1 ';
986 self
::populate(self
::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
989 return self
::$staticGroup;
993 * Get all Relationship Types from database.
995 * The static array group is returned, and if it's
996 * called the first time, the <b>RelationshipType DAO</b> is used
997 * to get all the relationship types.
999 * Note: any database errors will be trapped by the DAO.
1001 * @param string $valueColumnName
1002 * Db column name/label.
1003 * @param bool $reset
1004 * Reset relationship types if true.
1005 * @param bool $isActive
1006 * Filter by is_active. NULL to disable.
1009 * array reference of all relationship types.
1011 public static function &relationshipType($valueColumnName = 'label', $reset = FALSE, $isActive = 1) {
1012 $cacheKey = $valueColumnName . '::' . $isActive;
1013 if (!CRM_Utils_Array
::value($cacheKey, self
::$relationshipType) ||
$reset) {
1014 self
::$relationshipType[$cacheKey] = array();
1016 //now we have name/label columns CRM-3336
1017 $column_a_b = "{$valueColumnName}_a_b";
1018 $column_b_a = "{$valueColumnName}_b_a";
1020 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1021 $relationshipTypeDAO->selectAdd();
1022 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1023 if ($isActive !== NULL) {
1024 $relationshipTypeDAO->is_active
= $isActive;
1026 $relationshipTypeDAO->find();
1027 while ($relationshipTypeDAO->fetch()) {
1029 self
::$relationshipType[$cacheKey][$relationshipTypeDAO->id
] = array(
1030 'id' => $relationshipTypeDAO->id
,
1031 $column_a_b => $relationshipTypeDAO->$column_a_b,
1032 $column_b_a => $relationshipTypeDAO->$column_b_a,
1033 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1034 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1035 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1036 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1041 return self
::$relationshipType[$cacheKey];
1045 * Get all the ISO 4217 currency codes
1047 * so far, we use this for validation only, so there's no point of putting this into the database
1051 * array reference of all currency codes
1053 public static function ¤cyCode() {
1054 if (!self
::$currencyCode) {
1055 self
::$currencyCode = array(
1325 return self
::$currencyCode;
1329 * Get all the County from database.
1331 * The static array county is returned, and if it's
1332 * called the first time, the <b>County DAO</b> is used
1333 * to get all the Counties.
1335 * Note: any database errors will be trapped by the DAO.
1338 * @param bool|int $id - Optional id to return
1341 * array reference of all Counties
1343 public static function &county($id = FALSE) {
1344 if (!self
::$county) {
1346 $config = CRM_Core_Config
::singleton();
1347 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1348 self
::populate(self
::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1351 if (array_key_exists($id, self
::$county)) {
1352 return self
::$county[$id];
1355 return CRM_Core_DAO
::$_nullObject;
1358 return self
::$county;
1362 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1363 * Get all active payment processors
1365 * The static array paymentProcessor is returned
1369 * Get payment processors - default is to get only active ones.
1371 * Get test payment processors.
1373 * @param null $additionalCond
1376 * array of all payment processors
1378 public static function paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1379 $condition = "is_test = ";
1380 $condition .= ($test) ?
'1' : '0';
1382 if ($additionalCond) {
1383 $condition .= " AND ( $additionalCond ) ";
1386 // CRM-7178. Make sure we only include payment processors valid in this
1388 $condition .= " AND domain_id = " . CRM_Core_Config
::domainID();
1390 $cacheKey = $condition . '_' . (int) $all;
1391 if (!isset(self
::$paymentProcessor[$cacheKey])) {
1392 self
::populate(self
::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1395 return self
::$paymentProcessor[$cacheKey];
1399 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1401 * The static array paymentProcessorType is returned
1405 * Get payment processors - default is to get only active ones.
1408 * @param string $return
1411 * array of all payment processor types
1413 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1414 $cacheKey = $id . '_' . $return;
1415 if (empty(self
::$paymentProcessorType[$cacheKey])) {
1416 self
::populate(self
::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1418 if ($id && CRM_Utils_Array
::value($id, self
::$paymentProcessorType[$cacheKey])) {
1419 return self
::$paymentProcessorType[$cacheKey][$id];
1421 return self
::$paymentProcessorType[$cacheKey];
1425 * Get all the World Regions from Database.
1431 * array reference of all World Regions
1433 public static function &worldRegion($id = FALSE) {
1434 if (!self
::$worldRegions) {
1435 self
::populate(self
::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1439 if (array_key_exists($id, self
::$worldRegions)) {
1440 return self
::$worldRegions[$id];
1443 return CRM_Core_DAO
::$_nullObject;
1447 return self
::$worldRegions;
1451 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1453 * Get all Activity Statuses.
1455 * The static array activityStatus is returned
1458 * @param string $column
1461 * array reference of all activity statuses
1463 public static function &activityStatus($column = 'label') {
1464 if (NULL === self
::$activityStatus) {
1465 self
::$activityStatus = array();
1467 if (!array_key_exists($column, self
::$activityStatus)) {
1468 self
::$activityStatus[$column] = array();
1470 self
::$activityStatus[$column] = CRM_Core_OptionGroup
::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1473 return self
::$activityStatus[$column];
1477 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1479 * Get all Visibility levels.
1481 * The static array visibility is returned
1484 * @param string $column
1487 * array reference of all Visibility levels.
1489 public static function &visibility($column = 'label') {
1490 if (!isset(self
::$visibility)) {
1491 self
::$visibility = array();
1494 if (!isset(self
::$visibility[$column])) {
1495 self
::$visibility[$column] = CRM_Core_OptionGroup
::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1498 return self
::$visibility[$column];
1502 * @param int $countryID
1503 * @param string $field
1507 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1508 static $_cache = NULL;
1510 $cacheKey = "{$countryID}_{$field}";
1515 if (!empty($_cache[$cacheKey])) {
1516 return $_cache[$cacheKey];
1520 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1521 FROM civicrm_state_province
1522 WHERE country_id = %1
1531 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1534 while ($dao->fetch()) {
1535 $result[$dao->id
] = $dao->name
;
1538 // localise the stateProvince names if in an non-en_US locale
1539 $config = CRM_Core_Config
::singleton();
1540 $tsLocale = CRM_Core_I18n
::getLocale();
1541 if ($tsLocale != '' and $tsLocale != 'en_US') {
1542 $i18n = CRM_Core_I18n
::singleton();
1543 $i18n->localizeArray($result, array(
1544 'context' => 'province',
1546 $result = CRM_Utils_Array
::asort($result);
1549 $_cache[$cacheKey] = $result;
1551 CRM_Utils_Hook
::buildStateProvinceForCountry($countryID, $result);
1557 * @param int $stateID
1561 public static function &countyForState($stateID) {
1562 if (is_array($stateID)) {
1563 $states = implode(", ", $stateID);
1565 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1567 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1568 WHERE civicrm_county.state_province_id in ( $states )
1569 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1571 $dao = CRM_Core_DAO
::executeQuery($query);
1574 while ($dao->fetch()) {
1575 $result[$dao->id
] = $dao->abbreviation
. ': ' . $dao->name
;
1580 static $_cache = NULL;
1582 $cacheKey = "{$stateID}_name";
1587 if (!empty($_cache[$cacheKey])) {
1588 return $_cache[$cacheKey];
1592 SELECT civicrm_county.name name, civicrm_county.id id
1594 WHERE state_province_id = %1
1603 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1606 while ($dao->fetch()) {
1607 $result[$dao->id
] = $dao->name
;
1615 * Given a state ID return the country ID, this allows
1616 * us to populate forms and values for downstream code
1618 * @param int $stateID
1621 * the country id that the state belongs to
1623 public static function countryIDForStateID($stateID) {
1624 if (empty($stateID)) {
1630 FROM civicrm_state_province
1633 $params = array(1 => array($stateID, 'Integer'));
1635 return CRM_Core_DAO
::singleValueQuery($query, $params);
1639 * Get all types of Greetings.
1641 * The static array of greeting is returned
1645 * Get All Email Greetings - default is to get only active ones.
1647 * @param string $columnName
1650 * array reference of all greetings.
1652 public static function greeting($filter, $columnName = 'label') {
1653 $index = $filter['greeting_type'] . '_' . $columnName;
1655 // also add contactType to the array
1656 $contactType = CRM_Utils_Array
::value('contact_type', $filter);
1658 $index .= '_' . $contactType;
1661 if (NULL === self
::$greeting) {
1662 self
::$greeting = array();
1665 if (!CRM_Utils_Array
::value($index, self
::$greeting)) {
1666 $filterCondition = NULL;
1668 $filterVal = 'v.filter =';
1669 switch ($contactType) {
1678 case 'Organization':
1682 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1685 self
::$greeting[$index] = CRM_Core_OptionGroup
::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1688 return self
::$greeting[$index];
1692 * Construct array of default greeting values for contact type.
1696 * array reference of default greetings.
1698 public static function &greetingDefaults() {
1699 if (!self
::$greetingDefaults) {
1700 $defaultGreetings = array();
1701 $contactTypes = self
::get('CRM_Contact_DAO_Contact', 'contact_type', array(
1702 'keyColumn' => 'id',
1703 'labelColumn' => 'name',
1706 foreach ($contactTypes as $filter => $contactType) {
1707 $filterCondition = " AND (v.filter = 0 OR v.filter = $filter) AND v.is_default = 1 ";
1709 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1710 $tokenVal = CRM_Core_OptionGroup
::values($greeting, NULL, NULL, NULL, $filterCondition, 'label');
1711 $defaultGreetings[$contactType][$greeting] = $tokenVal;
1715 self
::$greetingDefaults = $defaultGreetings;
1718 return self
::$greetingDefaults;
1722 * Get all extensions.
1724 * The static array extensions
1726 * FIXME: This is called by civix but not by any core code. We
1727 * should provide an API call which civix can use instead.
1731 * array($fullyQualifiedName => $label) list of extensions
1733 public static function &getExtensions() {
1734 if (!self
::$extensions) {
1735 self
::$extensions = array();
1737 SELECT full_name, label
1738 FROM civicrm_extension
1741 $dao = CRM_Core_DAO
::executeQuery($sql);
1742 while ($dao->fetch()) {
1743 self
::$extensions[$dao->full_name
] = $dao->label
;
1747 return self
::$extensions;
1751 * Get all options values.
1753 * The static array option values is returned
1756 * @param bool $optionGroupName
1757 * Get All Option Group values- default is to get only active ones.
1760 * @param null $condition
1763 * array reference of all Option Group Name
1765 public static function accountOptionValues($optionGroupName, $id = NULL, $condition = NULL) {
1766 $cacheKey = $optionGroupName . '_' . $condition;
1767 if (empty(self
::$accountOptionValues[$cacheKey])) {
1768 self
::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup
::values($optionGroupName, FALSE, FALSE, FALSE, $condition);
1771 return CRM_Utils_Array
::value($id, self
::$accountOptionValues[$cacheKey]);
1774 return self
::$accountOptionValues[$cacheKey];
1778 * Fetch the list of active extensions of type 'module'
1780 * @param bool $fresh
1781 * Whether to forcibly reload extensions list from canonical store.
1784 * array(array('prefix' => $, 'file' => $))
1786 public static function getModuleExtensions($fresh = FALSE) {
1787 return CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles($fresh);
1792 * Get all tax rates.
1794 * The static array tax rates is returned
1797 * array list of tax rates with the financial type
1799 public static function getTaxRates() {
1800 if (!isset(Civi
::$statics[__CLASS__
]['taxRates'])) {
1801 Civi
::$statics[__CLASS__
]['taxRates'] = array();
1802 $option = civicrm_api3('option_value', 'get', array(
1804 'option_group_id' => 'account_relationship',
1805 'name' => 'Sales Tax Account is',
1808 if ($option['count'] !== 0) {
1809 if ($option['count'] > 1) {
1810 foreach ($option['values'] as $opt) {
1811 $value[] = $opt['value'];
1815 $value[] = $option['values'][0]['value'];
1817 $where = 'AND efa.account_relationship IN (' . implode(', ', $value) . ' )';
1823 SELECT fa.tax_rate, efa.entity_id
1824 FROM civicrm_entity_financial_account efa
1825 INNER JOIN civicrm_financial_account fa ON fa.id = efa.financial_account_id
1826 WHERE efa.entity_table = 'civicrm_financial_type'
1828 AND fa.is_active = 1";
1829 $dao = CRM_Core_DAO
::executeQuery($sql);
1830 while ($dao->fetch()) {
1831 Civi
::$statics[__CLASS__
]['taxRates'][$dao->entity_id
] = $dao->tax_rate
;
1835 return Civi
::$statics[__CLASS__
]['taxRates'];