3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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;
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 return call_user_func(Civi\Core\Resolver
::singleton()->get($pseudoconstant['callback']));
258 // Merge params with schema defaults
260 'condition' => CRM_Utils_Array
::value('condition', $pseudoconstant, array()),
261 'keyColumn' => CRM_Utils_Array
::value('keyColumn', $pseudoconstant),
262 'labelColumn' => CRM_Utils_Array
::value('labelColumn', $pseudoconstant),
265 if ($context == 'abbreviate') {
266 switch ($fieldName) {
267 case 'state_province_id':
268 $params['labelColumn'] = 'abbreviation';
272 $params['labelColumn'] = 'iso_code';
279 // Fetch option group from option_value table
280 if (!empty($pseudoconstant['optionGroupName'])) {
281 if ($context == 'validate') {
282 $params['labelColumn'] = 'name';
284 if ($context == 'match') {
285 $params['keyColumn'] = 'name';
287 // Call our generic fn for retrieving from the option_value table
288 $options = CRM_Core_OptionGroup
::values(
289 $pseudoconstant['optionGroupName'],
293 $params['condition'] ?
' AND ' . implode(' AND ', (array) $params['condition']) : NULL,
294 $params['labelColumn'] ?
$params['labelColumn'] : 'label',
295 $params['onlyActive'],
297 $params['keyColumn'] ?
$params['keyColumn'] : 'value'
299 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $options, $params);
303 // Fetch options from other tables
304 if (!empty($pseudoconstant['table'])) {
305 // Normalize params so the serialized cache string will be consistent.
306 CRM_Utils_Array
::remove($params, 'flip', 'fresh');
308 $cacheKey = $daoName . $fieldName . serialize($params);
310 // Retrieve cached options
311 if (isset(self
::$cache[$cacheKey]) && empty($params['fresh'])) {
312 $output = self
::$cache[$cacheKey];
315 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($pseudoconstant['table']);
316 if (!class_exists($daoName)) {
319 // Get list of fields for the option table
320 $dao = new $daoName();
321 $availableFields = array_keys($dao->fieldKeys());
324 $select = "SELECT %1 AS id, %2 AS label";
327 $order = "ORDER BY %2";
329 // Use machine name in certain contexts
330 if ($context == 'validate' ||
$context == 'match') {
331 $nameField = $context == 'validate' ?
'labelColumn' : 'keyColumn';
332 if (!empty($pseudoconstant['nameColumn'])) {
333 $params[$nameField] = $pseudoconstant['nameColumn'];
335 elseif (in_array('name', $availableFields)) {
336 $params[$nameField] = 'name';
339 // Condition param can be passed as an sql clause string or an array of clauses
340 if (!empty($params['condition'])) {
341 $wheres[] = implode(' AND ', (array) $params['condition']);
343 // onlyActive param will automatically filter on common flags
344 if (!empty($params['onlyActive'])) {
345 foreach (array('is_active' => 1, 'is_deleted' => 0, 'is_test' => 0, 'is_hidden' => 0) as $flag => $val) {
346 if (in_array($flag, $availableFields)) {
347 $wheres[] = "$flag = $val";
351 // Filter domain specific options
352 if (in_array('domain_id', $availableFields)) {
353 $wheres[] = 'domain_id = ' . CRM_Core_Config
::domainID();
355 $queryParams = array(
356 1 => array($params['keyColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
357 2 => array($params['labelColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
358 3 => array($pseudoconstant['table'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
),
360 // Add orderColumn param
361 if (!empty($params['orderColumn'])) {
362 $queryParams[4] = array($params['orderColumn'], 'String', CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
);
363 $order = "ORDER BY %4";
365 // Support no sorting if $params[orderColumn] is FALSE
366 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
369 // Default to 'weight' if that column exists
370 elseif (in_array('weight', $availableFields)) {
371 $order = "ORDER BY weight";
375 $query = "$select $from";
377 $query .= " WHERE " . implode($wheres, ' AND ');
379 $query .= ' ' . $order;
380 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
381 while ($dao->fetch()) {
382 $output[$dao->id
] = $dao->label
;
386 if (!empty($params['localize']) ||
$pseudoconstant['table'] == 'civicrm_country' ||
$pseudoconstant['table'] == 'civicrm_state_province') {
387 $I18nParams = array();
388 if ($pseudoconstant['table'] == 'civicrm_country') {
389 $I18nParams['context'] = 'country';
391 if ($pseudoconstant['table'] == 'civicrm_state_province') {
392 $I18nParams['context'] = 'province';
394 $i18n = CRM_Core_I18n
::singleton();
395 $i18n->localizeArray($output, $I18nParams);
396 // Maintain sort by label
397 if ($order == "ORDER BY %2") {
398 CRM_Utils_Array
::asort($output);
401 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $output, $params);
402 self
::$cache[$cacheKey] = $output;
404 return $flip ?
array_flip($output) : $output;
408 // Return "Yes" and "No" for boolean fields
409 elseif (CRM_Utils_Array
::value('type', $fieldSpec) === CRM_Utils_Type
::T_BOOLEAN
) {
410 $output = $context == 'validate' ?
array(0, 1) : CRM_Core_SelectValues
::boolean();
411 CRM_Utils_Hook
::fieldOptions($entity, $fieldName, $output, $params);
412 return $flip ?
array_flip($output) : $output;
414 // If we're still here, it's an error. Return FALSE.
419 * Fetch the translated label for a field given its key.
421 * @param string $baoName
422 * @param string $fieldName
423 * @param string|Int $key
425 * TODO: Accept multivalued input?
427 * @return bool|null|string
428 * FALSE if the given field has no associated option list
429 * NULL if the given key has no corresponding option
430 * String if label is found
432 public static function getLabel($baoName, $fieldName, $key) {
433 $values = $baoName::buildOptions($fieldName, 'get');
434 if ($values === FALSE) {
437 return CRM_Utils_Array
::value($key, $values);
441 * Fetch the machine name for a field given its key.
443 * @param string $baoName
444 * @param string $fieldName
445 * @param string|Int $key
447 * @return bool|null|string
448 * FALSE if the given field has no associated option list
449 * NULL if the given key has no corresponding option
450 * String if label is found
452 public static function getName($baoName, $fieldName, $key) {
453 $values = $baoName::buildOptions($fieldName, 'validate');
454 if ($values === FALSE) {
457 return CRM_Utils_Array
::value($key, $values);
461 * Fetch the key for a field option given its name.
463 * @param string $baoName
464 * @param string $fieldName
465 * @param string|Int $value
467 * @return bool|null|string|int
468 * FALSE if the given field has no associated option list
469 * NULL if the given key has no corresponding option
470 * String|Number if key is found
472 public static function getKey($baoName, $fieldName, $value) {
473 $values = $baoName::buildOptions($fieldName, 'validate');
474 if ($values === FALSE) {
477 return CRM_Utils_Array
::key($value, $values);
481 * Lookup the admin page at which a field's option list can be edited
483 * @return string|null
485 public static function getOptionEditUrl($fieldSpec) {
486 // If it's an option group, that's easy
487 if (!empty($fieldSpec['pseudoconstant']['optionGroupName'])) {
488 return 'civicrm/admin/options/' . $fieldSpec['pseudoconstant']['optionGroupName'];
490 // For everything else...
491 elseif (!empty($fieldSpec['pseudoconstant']['table'])) {
492 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($fieldSpec['pseudoconstant']['table']);
496 // We don't have good mapping so have to do a bit of guesswork from the menu
497 list(, $parent, , $child) = explode('_', $daoName);
498 $sql = "SELECT path FROM civicrm_menu
499 WHERE page_callback LIKE '%CRM_Admin_Page_$child%' OR page_callback LIKE '%CRM_{$parent}_Page_$child%'
500 ORDER BY page_callback
502 return CRM_Core_Dao
::singleValueQuery($sql);
508 * DEPRECATED generic populate method.
509 * All pseudoconstant functions that use this method are also @deprecated
511 * The static array $var is populated from the db
512 * using the <b>$name DAO</b>.
514 * Note: any database errors will be trapped by the DAO.
517 * The associative array we will fill.
518 * @param string $name
519 * The name of the DAO.
521 * Get all objects. default is to get only active ones.
522 * @param string $retrieve
523 * The field that we are interested in (normally name, differs in some objects).
524 * @param string $filter
525 * The field that we want to filter the result set with.
526 * @param string $condition
527 * The condition that gets passed to the final query as the WHERE clause.
529 * @param bool $orderby
535 public static function populate(
540 $filter = 'is_active',
546 $cacheKey = "CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}";
547 $cache = CRM_Utils_Cache
::singleton();
548 $var = $cache->get($cacheKey);
549 if ($var && empty($force)) {
553 $object = new $name();
555 $object->selectAdd();
556 $object->selectAdd("$key, $retrieve");
558 $object->whereAdd($condition);
562 $object->orderBy($retrieve);
565 $object->orderBy($orderby);
569 $object->$filter = 1;
574 while ($object->fetch()) {
575 $var[$object->$key] = $object->$retrieve;
578 $cache->set($cacheKey, $var);
582 * Flush given pseudoconstant so it can be reread from db.
583 * nex time it's requested.
586 * @param bool|string $name pseudoconstant to be flushed
588 public static function flush($name = 'cache') {
589 if (isset(self
::$
$name)) {
592 if ($name == 'cache') {
593 CRM_Core_OptionGroup
::flushAll();
598 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
600 * Get all Activty types.
602 * The static array activityType is returned
606 * array reference of all activity types.
608 public static function &activityType() {
609 $args = func_get_args();
610 $all = CRM_Utils_Array
::value(0, $args, TRUE);
611 $includeCaseActivities = CRM_Utils_Array
::value(1, $args, FALSE);
612 $reset = CRM_Utils_Array
::value(2, $args, FALSE);
613 $returnColumn = CRM_Utils_Array
::value(3, $args, 'label');
614 $includeCampaignActivities = CRM_Utils_Array
::value(4, $args, FALSE);
615 $onlyComponentActivities = CRM_Utils_Array
::value(5, $args, FALSE);
616 $index = (int) $all . '_' . $returnColumn . '_' . (int) $includeCaseActivities;
617 $index .= '_' . (int) $includeCampaignActivities;
618 $index .= '_' . (int) $onlyComponentActivities;
620 if (NULL === self
::$activityType) {
621 self
::$activityType = array();
624 if (!isset(self
::$activityType[$index]) ||
$reset) {
627 $condition = 'AND filter = 0';
629 $componentClause = " v.component_id IS NULL";
630 if ($onlyComponentActivities) {
631 $componentClause = " v.component_id IS NOT NULL";
634 $componentIds = array();
635 $compInfo = CRM_Core_Component
::getEnabledComponents();
637 // build filter for listing activity types only if their
638 // respective components are enabled
639 foreach ($compInfo as $compName => $compObj) {
640 if ($compName == 'CiviCase') {
641 if ($includeCaseActivities) {
642 $componentIds[] = $compObj->componentID
;
645 elseif ($compName == 'CiviCampaign') {
646 if ($includeCampaignActivities) {
647 $componentIds[] = $compObj->componentID
;
651 $componentIds[] = $compObj->componentID
;
655 if (count($componentIds)) {
656 $componentIds = implode(',', $componentIds);
657 $componentClause = " ($componentClause OR v.component_id IN ($componentIds))";
658 if ($onlyComponentActivities) {
659 $componentClause = " ( v.component_id IN ($componentIds ) )";
662 $condition = $condition . ' AND ' . $componentClause;
664 self
::$activityType[$index] = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
666 return self
::$activityType[$index];
670 * Get all the State/Province from database.
672 * The static array stateProvince is returned, and if it's
673 * called the first time, the <b>State Province DAO</b> is used
674 * to get all the States.
676 * Note: any database errors will be trapped by the DAO.
679 * @param bool|int $id - Optional id to return
684 * array reference of all State/Provinces.
686 public static function &stateProvince($id = FALSE, $limit = TRUE) {
687 if (($id && !CRM_Utils_Array
::value($id, self
::$stateProvince)) ||
!self
::$stateProvince ||
!$id) {
688 $whereClause = FALSE;
690 $countryIsoCodes = self
::countryIsoCode();
691 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
693 foreach ($limitCodes as $code) {
694 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
696 if (!empty($limitIds)) {
697 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
700 $whereClause = FALSE;
703 self
::populate(self
::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
705 // localise the province names if in an non-en_US locale
707 if ($tsLocale != '' and $tsLocale != 'en_US') {
708 $i18n = CRM_Core_I18n
::singleton();
709 $i18n->localizeArray(self
::$stateProvince, array(
710 'context' => 'province',
712 self
::$stateProvince = CRM_Utils_Array
::asort(self
::$stateProvince);
716 if (array_key_exists($id, self
::$stateProvince)) {
717 return self
::$stateProvince[$id];
724 return self
::$stateProvince;
728 * Get all the State/Province abbreviations from the database.
730 * Same as above, except gets the abbreviations instead of the names.
733 * @param bool|int $id - Optional id to return
738 * array reference of all State/Province abbreviations.
740 public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
744 FROM civicrm_state_province
752 return CRM_Core_DAO
::singleValueQuery($query, $params);
755 if (!self
::$stateProvinceAbbreviation ||
!$id) {
757 $whereClause = FALSE;
760 $countryIsoCodes = self
::countryIsoCode();
761 $limitCodes = CRM_Core_BAO_Country
::provinceLimit();
763 foreach ($limitCodes as $code) {
764 $tmpArray = array_keys($countryIsoCodes, $code);
766 if (!empty($tmpArray)) {
767 $limitIds[] = array_shift($tmpArray);
770 if (!empty($limitIds)) {
771 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
774 self
::populate(self
::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
778 if (array_key_exists($id, self
::$stateProvinceAbbreviation)) {
779 return self
::$stateProvinceAbbreviation[$id];
786 return self
::$stateProvinceAbbreviation;
790 * Get all the countries from database.
792 * The static array country is returned, and if it's
793 * called the first time, the <b>Country DAO</b> is used
794 * to get all the countries.
796 * Note: any database errors will be trapped by the DAO.
799 * @param bool|int $id - Optional id to return
801 * @param bool $applyLimit
804 * array reference of all countries.
806 public static function country($id = FALSE, $applyLimit = TRUE) {
807 if (($id && !CRM_Utils_Array
::value($id, self
::$country)) ||
!self
::$country ||
!$id) {
809 $config = CRM_Core_Config
::singleton();
810 $limitCodes = array();
813 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
814 // (ensuring it's a subset of the legal values)
815 // K/P: We need to fix this, i dont think it works with new setting files
816 $limitCodes = CRM_Core_BAO_Country
::countryLimit();
817 if (!is_array($limitCodes)) {
819 $config->countryLimit
=> 1,
823 $limitCodes = array_intersect(self
::countryIsoCode(), $limitCodes);
826 if (count($limitCodes)) {
827 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
833 self
::populate(self
::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
835 // if default country is set, percolate it to the top
836 if ($config->defaultContactCountry()) {
837 $countryIsoCodes = self
::countryIsoCode();
838 $defaultID = array_search($config->defaultContactCountry(), $countryIsoCodes);
839 if ($defaultID !== FALSE) {
840 $default[$defaultID] = CRM_Utils_Array
::value($defaultID, self
::$country);
841 self
::$country = $default + self
::$country;
845 // localise the country names if in an non-en_US locale
847 if ($tsLocale != '' and $tsLocale != 'en_US') {
848 $i18n = CRM_Core_I18n
::singleton();
849 $i18n->localizeArray(self
::$country, array(
850 'context' => 'country',
852 self
::$country = CRM_Utils_Array
::asort(self
::$country);
856 if (array_key_exists($id, self
::$country)) {
857 return self
::$country[$id];
860 return CRM_Core_DAO
::$_nullObject;
863 return self
::$country;
867 * Get all the country ISO Code abbreviations from the database.
869 * The static array countryIsoCode is returned, and if it's
870 * called the first time, the <b>Country DAO</b> is used
871 * to get all the countries' ISO codes.
873 * Note: any database errors will be trapped by the DAO.
879 * array reference of all country ISO codes.
881 public static function &countryIsoCode($id = FALSE) {
882 if (!self
::$countryIsoCode) {
883 self
::populate(self
::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
886 if (array_key_exists($id, self
::$countryIsoCode)) {
887 return self
::$countryIsoCode[$id];
890 return CRM_Core_DAO
::$_nullObject;
893 return self
::$countryIsoCode;
897 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
899 * Get all groups from database
901 * The static array group is returned, and if it's
902 * called the first time, the <b>Group DAO</b> is used
903 * to get all the groups.
905 * Note: any database errors will be trapped by the DAO.
907 * @param string $groupType
908 * Type of group(Access/Mailing).
909 * @param bool $excludeHidden
910 * Exclude hidden groups.
914 * array reference of all groups.
916 public static function allGroup($groupType = NULL, $excludeHidden = TRUE) {
917 $condition = CRM_Contact_BAO_Group
::groupTypeCondition($groupType, $excludeHidden);
920 self
::$group = array();
923 $groupKey = ($groupType ?
$groupType : 'null') . !empty($excludeHidden);
925 if (!isset(self
::$group[$groupKey])) {
926 self
::$group[$groupKey] = NULL;
927 self
::populate(self
::$group[$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
929 return self
::$group[$groupKey];
933 * Create or get groups iterator (iterates over nested groups in a
936 * The GroupNesting instance is returned; it's created if this is being
937 * called for the first time
941 * @param bool $styledLabels
943 * @return CRM_Contact_BAO_GroupNesting
945 public static function &groupIterator($styledLabels = FALSE) {
946 if (!self
::$groupIterator) {
947 // When used as an object, GroupNesting implements Iterator
948 // and iterates nested groups in a logical manner for us
949 self
::$groupIterator = new CRM_Contact_BAO_GroupNesting($styledLabels);
951 return self
::$groupIterator;
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.
963 * @param string $groupType
964 * Type of group(Access/Mailing).
965 * @param bool $excludeHidden
966 * Exclude hidden groups.
970 * array reference of all groups.
972 public static function group($groupType = NULL, $excludeHidden = TRUE) {
973 return CRM_Core_Permission
::group($groupType, $excludeHidden);
977 * Fetch groups in a nested format suitable for use in select form element.
978 * @param bool $checkPermissions
979 * @param string|null $groupType
980 * @param bool $excludeHidden
983 public static function nestedGroup($checkPermissions = TRUE, $groupType = NULL, $excludeHidden = TRUE) {
984 $groups = $checkPermissions ? self
::group($groupType, $excludeHidden) : self
::allGroup($groupType, $excludeHidden);
985 return CRM_Contact_BAO_Group
::getGroupsHierarchy($groups, NULL, ' ', TRUE);
989 * Get all permissioned groups from database.
991 * The static array group is returned, and if it's
992 * called the first time, the <b>Group DAO</b> is used
993 * to get all the groups.
995 * Note: any database errors will be trapped by the DAO.
998 * @param bool $onlyPublic
999 * @param null $groupType
1000 * @param bool $excludeHidden
1003 * array reference of all groups.
1005 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
1006 if (!self
::$staticGroup) {
1007 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
1009 $condition .= " AND visibility != 'User and User Admin Only'";
1013 $condition .= ' AND ' . CRM_Contact_BAO_Group
::groupTypeCondition($groupType);
1016 if ($excludeHidden) {
1017 $condition .= ' AND is_hidden != 1 ';
1020 self
::populate(self
::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
1023 return self
::$staticGroup;
1027 * Get all Relationship Types from database.
1029 * The static array group is returned, and if it's
1030 * called the first time, the <b>RelationshipType DAO</b> is used
1031 * to get all the relationship types.
1033 * Note: any database errors will be trapped by the DAO.
1035 * @param string $valueColumnName
1036 * Db column name/label.
1037 * @param bool $reset
1038 * Reset relationship types if true.
1039 * @param bool|NULL $isActive
1040 * Filter by is_active. NULL to disable.
1043 * array reference of all relationship types.
1045 public static function &relationshipType($valueColumnName = 'label', $reset = FALSE, $isActive = 1) {
1046 $cacheKey = $valueColumnName . '::' . $isActive;
1047 if (!CRM_Utils_Array
::value($cacheKey, self
::$relationshipType) ||
$reset) {
1048 self
::$relationshipType[$cacheKey] = array();
1050 //now we have name/label columns CRM-3336
1051 $column_a_b = "{$valueColumnName}_a_b";
1052 $column_b_a = "{$valueColumnName}_b_a";
1054 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1055 $relationshipTypeDAO->selectAdd();
1056 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1057 if ($isActive !== NULL) {
1058 $relationshipTypeDAO->is_active
= $isActive;
1060 $relationshipTypeDAO->find();
1061 while ($relationshipTypeDAO->fetch()) {
1063 self
::$relationshipType[$cacheKey][$relationshipTypeDAO->id
] = array(
1064 'id' => $relationshipTypeDAO->id
,
1065 $column_a_b => $relationshipTypeDAO->$column_a_b,
1066 $column_b_a => $relationshipTypeDAO->$column_b_a,
1067 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1068 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1069 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1070 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1075 return self
::$relationshipType[$cacheKey];
1079 * Get all the ISO 4217 currency codes
1081 * so far, we use this for validation only, so there's no point of putting this into the database
1085 * array reference of all currency codes
1087 public static function ¤cyCode() {
1088 if (!self
::$currencyCode) {
1089 self
::$currencyCode = array(
1359 return self
::$currencyCode;
1363 * Get all the County from database.
1365 * The static array county is returned, and if it's
1366 * called the first time, the <b>County DAO</b> is used
1367 * to get all the Counties.
1369 * Note: any database errors will be trapped by the DAO.
1372 * @param bool|int $id - Optional id to return
1375 * array reference of all Counties
1377 public static function &county($id = FALSE) {
1378 if (!self
::$county) {
1380 $config = CRM_Core_Config
::singleton();
1381 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1382 self
::populate(self
::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1385 if (array_key_exists($id, self
::$county)) {
1386 return self
::$county[$id];
1389 return CRM_Core_DAO
::$_nullObject;
1392 return self
::$county;
1396 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1397 * Get all active payment processors
1399 * The static array paymentProcessor is returned
1403 * Get payment processors - default is to get only active ones.
1405 * Get test payment processors.
1407 * @param null $additionalCond
1410 * array of all payment processors
1412 public static function paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1413 $condition = "is_test = ";
1414 $condition .= ($test) ?
'1' : '0';
1416 if ($additionalCond) {
1417 $condition .= " AND ( $additionalCond ) ";
1420 // CRM-7178. Make sure we only include payment processors valid in this
1422 $condition .= " AND domain_id = " . CRM_Core_Config
::domainID();
1424 $cacheKey = $condition . '_' . (int) $all;
1425 if (!isset(self
::$paymentProcessor[$cacheKey])) {
1426 self
::populate(self
::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1429 return self
::$paymentProcessor[$cacheKey];
1433 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1435 * The static array paymentProcessorType is returned
1439 * Get payment processors - default is to get only active ones.
1442 * @param string $return
1445 * array of all payment processor types
1447 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1448 $cacheKey = $id . '_' . $return;
1449 if (empty(self
::$paymentProcessorType[$cacheKey])) {
1450 self
::populate(self
::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1452 if ($id && CRM_Utils_Array
::value($id, self
::$paymentProcessorType[$cacheKey])) {
1453 return self
::$paymentProcessorType[$cacheKey][$id];
1455 return self
::$paymentProcessorType[$cacheKey];
1459 * Get all the World Regions from Database.
1465 * array reference of all World Regions
1467 public static function &worldRegion($id = FALSE) {
1468 if (!self
::$worldRegions) {
1469 self
::populate(self
::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1473 if (array_key_exists($id, self
::$worldRegions)) {
1474 return self
::$worldRegions[$id];
1477 return CRM_Core_DAO
::$_nullObject;
1481 return self
::$worldRegions;
1485 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1487 * Get all Activity Statuses.
1489 * The static array activityStatus is returned
1492 * @param string $column
1495 * array reference of all activity statuses
1497 public static function &activityStatus($column = 'label') {
1498 if (NULL === self
::$activityStatus) {
1499 self
::$activityStatus = array();
1501 if (!array_key_exists($column, self
::$activityStatus)) {
1502 self
::$activityStatus[$column] = array();
1504 self
::$activityStatus[$column] = CRM_Core_OptionGroup
::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1507 return self
::$activityStatus[$column];
1511 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1513 * Get all Visibility levels.
1515 * The static array visibility is returned
1518 * @param string $column
1521 * array reference of all Visibility levels.
1523 public static function &visibility($column = 'label') {
1524 if (!isset(self
::$visibility)) {
1525 self
::$visibility = array();
1528 if (!isset(self
::$visibility[$column])) {
1529 self
::$visibility[$column] = CRM_Core_OptionGroup
::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1532 return self
::$visibility[$column];
1536 * @param int $countryID
1537 * @param string $field
1541 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1542 static $_cache = NULL;
1544 $cacheKey = "{$countryID}_{$field}";
1549 if (!empty($_cache[$cacheKey])) {
1550 return $_cache[$cacheKey];
1554 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1555 FROM civicrm_state_province
1556 WHERE country_id = %1
1565 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1568 while ($dao->fetch()) {
1569 $result[$dao->id
] = $dao->name
;
1572 // localise the stateProvince names if in an non-en_US locale
1573 $config = CRM_Core_Config
::singleton();
1575 if ($tsLocale != '' and $tsLocale != 'en_US') {
1576 $i18n = CRM_Core_I18n
::singleton();
1577 $i18n->localizeArray($result, array(
1578 'context' => 'province',
1580 $result = CRM_Utils_Array
::asort($result);
1583 $_cache[$cacheKey] = $result;
1585 CRM_Utils_Hook
::buildStateProvinceForCountry($countryID, $result);
1591 * @param int $stateID
1595 public static function &countyForState($stateID) {
1596 if (is_array($stateID)) {
1597 $states = implode(", ", $stateID);
1599 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1601 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1602 WHERE civicrm_county.state_province_id in ( $states )
1603 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1605 $dao = CRM_Core_DAO
::executeQuery($query);
1608 while ($dao->fetch()) {
1609 $result[$dao->id
] = $dao->abbreviation
. ': ' . $dao->name
;
1614 static $_cache = NULL;
1616 $cacheKey = "{$stateID}_name";
1621 if (!empty($_cache[$cacheKey])) {
1622 return $_cache[$cacheKey];
1626 SELECT civicrm_county.name name, civicrm_county.id id
1628 WHERE state_province_id = %1
1637 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1640 while ($dao->fetch()) {
1641 $result[$dao->id
] = $dao->name
;
1649 * Given a state ID return the country ID, this allows
1650 * us to populate forms and values for downstream code
1652 * @param int $stateID
1655 * the country id that the state belongs to
1657 public static function countryIDForStateID($stateID) {
1658 if (empty($stateID)) {
1659 return CRM_Core_DAO
::$_nullObject;
1664 FROM civicrm_state_province
1667 $params = array(1 => array($stateID, 'Integer'));
1669 return CRM_Core_DAO
::singleValueQuery($query, $params);
1673 * Get all types of Greetings.
1675 * The static array of greeting is returned
1679 * Get All Email Greetings - default is to get only active ones.
1681 * @param string $columnName
1684 * array reference of all greetings.
1686 public static function greeting($filter, $columnName = 'label') {
1687 $index = $filter['greeting_type'] . '_' . $columnName;
1689 // also add contactType to the array
1690 $contactType = CRM_Utils_Array
::value('contact_type', $filter);
1692 $index .= '_' . $contactType;
1695 if (NULL === self
::$greeting) {
1696 self
::$greeting = array();
1699 if (!CRM_Utils_Array
::value($index, self
::$greeting)) {
1700 $filterCondition = NULL;
1702 $filterVal = 'v.filter =';
1703 switch ($contactType) {
1712 case 'Organization':
1716 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1719 self
::$greeting[$index] = CRM_Core_OptionGroup
::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1722 return self
::$greeting[$index];
1726 * Construct array of default greeting values for contact type.
1730 * array reference of default greetings.
1732 public static function &greetingDefaults() {
1733 if (!self
::$greetingDefaults) {
1734 $defaultGreetings = array();
1735 $contactTypes = self
::get('CRM_Contact_DAO_Contact', 'contact_type', array(
1736 'keyColumn' => 'id',
1737 'labelColumn' => 'name',
1740 foreach ($contactTypes as $filter => $contactType) {
1741 $filterCondition = " AND (v.filter = 0 OR v.filter = $filter) AND v.is_default = 1 ";
1743 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
1744 $tokenVal = CRM_Core_OptionGroup
::values($greeting, NULL, NULL, NULL, $filterCondition, 'label');
1745 $defaultGreetings[$contactType][$greeting] = $tokenVal;
1749 self
::$greetingDefaults = $defaultGreetings;
1752 return self
::$greetingDefaults;
1756 * Get all extensions.
1758 * The static array extensions
1760 * FIXME: This is called by civix but not by any core code. We
1761 * should provide an API call which civix can use instead.
1765 * array($fullyQualifiedName => $label) list of extensions
1767 public static function &getExtensions() {
1768 if (!self
::$extensions) {
1769 self
::$extensions = array();
1771 SELECT full_name, label
1772 FROM civicrm_extension
1775 $dao = CRM_Core_DAO
::executeQuery($sql);
1776 while ($dao->fetch()) {
1777 self
::$extensions[$dao->full_name
] = $dao->label
;
1781 return self
::$extensions;
1785 * Get all options values.
1787 * The static array option values is returned
1790 * @param bool $optionGroupName
1791 * Get All Option Group values- default is to get only active ones.
1794 * @param null $condition
1797 * array reference of all Option Group Name
1799 public static function accountOptionValues($optionGroupName, $id = NULL, $condition = NULL) {
1800 $cacheKey = $optionGroupName . '_' . $condition;
1801 if (empty(self
::$accountOptionValues[$cacheKey])) {
1802 self
::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup
::values($optionGroupName, FALSE, FALSE, FALSE, $condition);
1805 return CRM_Utils_Array
::value($id, self
::$accountOptionValues[$cacheKey]);
1808 return self
::$accountOptionValues[$cacheKey];
1812 * Fetch the list of active extensions of type 'module'
1814 * @param bool $fresh
1815 * Whether to forcibly reload extensions list from canonical store.
1818 * array(array('prefix' => $, 'file' => $))
1820 public static function getModuleExtensions($fresh = FALSE) {
1821 return CRM_Extension_System
::singleton()->getMapper()->getActiveModuleFiles($fresh);
1826 * Get all tax rates.
1828 * The static array tax rates is returned
1831 * array list of tax rates with the financial type
1833 public static function getTaxRates() {
1834 if (!isset(Civi
::$statics[__CLASS__
]['taxRates'])) {
1835 Civi
::$statics[__CLASS__
]['taxRates'] = array();
1837 SELECT fa.tax_rate, efa.entity_id
1838 FROM civicrm_entity_financial_account efa
1839 INNER JOIN civicrm_financial_account fa ON fa.id = efa.financial_account_id
1840 INNER JOIN civicrm_option_value cov ON cov.value = efa.account_relationship
1841 INNER JOIN civicrm_option_group cog ON cog.id = cov.option_group_id
1842 WHERE efa.entity_table = 'civicrm_financial_type'
1843 AND cov.name = 'Sales Tax Account is'
1844 AND cog.name = 'account_relationship'
1845 AND fa.is_active = 1";
1846 $dao = CRM_Core_DAO
::executeQuery($sql);
1847 while ($dao->fetch()) {
1848 Civi
::$statics[__CLASS__
]['taxRates'][$dao->entity_id
] = $dao->tax_rate
;
1852 return Civi
::$statics[__CLASS__
]['taxRates'];