Merge pull request #14244 from greenpeace-cee/fix-contribution-overwrite
[civicrm-core.git] / CRM / Core / PseudoConstant.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * Stores all constants and pseudo constants for CRM application.
31 *
32 * examples of constants are "Contact Type" which will always be either
33 * 'Individual', 'Household', 'Organization'.
34 *
35 * pseudo constants are entities from the database whose values rarely
36 * change. examples are list of countries, states, location types,
37 * relationship types.
38 *
39 * currently we're getting the data from the underlying database. this
40 * will be reworked to use caching.
41 *
42 * Note: All pseudoconstants should be uninitialized or default to NULL.
43 * This provides greater consistency/predictability after flushing.
44 *
45 * @package CRM
46 * @copyright CiviCRM LLC (c) 2004-2019
47 */
48 class CRM_Core_PseudoConstant {
49
50 /**
51 * Static cache for pseudoconstant arrays.
52 * @var array
53 */
54 private static $cache;
55
56 /**
57 * activity type
58 * @var array
59 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
60 */
61 private static $activityType;
62
63 /**
64 * States, provinces
65 * @var array
66 */
67 private static $stateProvince;
68
69 /**
70 * Counties.
71 * @var array
72 */
73 private static $county;
74
75 /**
76 * States/provinces abbreviations
77 * @var array
78 */
79 private static $stateProvinceAbbreviation = [];
80
81 /**
82 * Country.
83 * @var array
84 */
85 private static $country;
86
87 /**
88 * CountryIsoCode.
89 * @var array
90 */
91 private static $countryIsoCode;
92
93 /**
94 * group
95 * @var array
96 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
97 */
98 private static $group;
99
100 /**
101 * RelationshipType
102 * @var array
103 */
104 private static $relationshipType;
105
106 /**
107 * Civicrm groups that are not smart groups
108 * @var array
109 */
110 private static $staticGroup;
111
112 /**
113 * Currency codes
114 * @var array
115 */
116 private static $currencyCode;
117
118 /**
119 * Payment processor
120 * @var array
121 */
122 private static $paymentProcessor;
123
124 /**
125 * Payment processor types
126 * @var array
127 */
128 private static $paymentProcessorType;
129
130 /**
131 * World Region
132 * @var array
133 */
134 private static $worldRegions;
135
136 /**
137 * activity status
138 * @var array
139 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
140 */
141 private static $activityStatus;
142
143 /**
144 * Visibility
145 * @var array
146 */
147 private static $visibility;
148
149 /**
150 * Greetings
151 * @var array
152 */
153 private static $greeting;
154
155 /**
156 * Extensions of type module
157 * @var array
158 */
159 private static $extensions;
160
161 /**
162 * Financial Account Type
163 * @var array
164 */
165 private static $accountOptionValues;
166
167 /**
168 * Low-level option getter, rarely accessed directly.
169 * NOTE: Rather than calling this function directly use CRM_*_BAO_*::buildOptions()
170 * @see https://docs.civicrm.org/dev/en/latest/framework/pseudoconstant/
171 *
172 * NOTE: If someone undertakes a refactoring of this, please consider the use-case of
173 * the Setting.getoptions API. There is no DAO/field, but it would be nice to use the
174 * same 'pseudoconstant' struct in *.settings.php. This means loosening the coupling
175 * between $field lookup and the $pseudoconstant evaluation.
176 *
177 * @param string $daoName
178 * @param string $fieldName
179 * @param array $params
180 * - name string name of the option group
181 * - flip boolean results are return in id => label format if false
182 * if true, the results are reversed
183 * - grouping boolean if true, return the value in 'grouping' column (currently unsupported for tables other than option_value)
184 * - localize boolean if true, localize the results before returning
185 * - condition string|array add condition(s) to the sql query - will be concatenated using 'AND'
186 * - keyColumn string the column to use for 'id'
187 * - labelColumn string the column to use for 'label'
188 * - orderColumn string the column to use for sorting, defaults to 'weight' column if one exists, else defaults to labelColumn
189 * - onlyActive boolean return only the action option values
190 * - fresh boolean ignore cache entries and go back to DB
191 * @param string $context : Context string
192 * @see CRM_Core_DAO::buildOptionsContext
193 *
194 * @return array|bool
195 * array on success, FALSE on error.
196 *
197 */
198 public static function get($daoName, $fieldName, $params = [], $context = NULL) {
199 CRM_Core_DAO::buildOptionsContext($context);
200 $flip = !empty($params['flip']);
201 // Historically this was 'false' but according to the notes in
202 // CRM_Core_DAO::buildOptionsContext it should be context dependent.
203 // timidly changing for 'search' only to fix world_region in search options.
204 $localizeDefault = in_array($context, ['search']) ? TRUE : FALSE;
205 // Merge params with defaults
206 $params += [
207 'grouping' => FALSE,
208 'localize' => $localizeDefault,
209 'onlyActive' => ($context == 'validate' || $context == 'get') ? FALSE : TRUE,
210 'fresh' => FALSE,
211 'context' => $context,
212 ];
213 $entity = CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getCanonicalClassName($daoName));
214
215 // Custom fields are not in the schema
216 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
217 $customField = new CRM_Core_BAO_CustomField();
218 $customField->id = (int) substr($fieldName, 7);
219 $options = $customField->getOptions($context);
220 if ($options && $flip) {
221 $options = array_flip($options);
222 }
223 return $options;
224 }
225
226 // Core field: load schema
227 $dao = new $daoName();
228 $fieldSpec = $dao->getFieldSpec($fieldName);
229
230 // Ensure we have the canonical name for this field
231 $fieldName = CRM_Utils_Array::value('name', $fieldSpec, $fieldName);
232
233 // Return false if field doesn't exist.
234 if (empty($fieldSpec)) {
235 return FALSE;
236 }
237
238 elseif (!empty($fieldSpec['pseudoconstant'])) {
239 $pseudoconstant = $fieldSpec['pseudoconstant'];
240
241 // if callback is specified..
242 if (!empty($pseudoconstant['callback'])) {
243 $fieldOptions = call_user_func(Civi\Core\Resolver::singleton()->get($pseudoconstant['callback']), $context);
244 //CRM-18223: Allow additions to field options via hook.
245 CRM_Utils_Hook::fieldOptions($entity, $fieldName, $fieldOptions, $params);
246 return $fieldOptions;
247 }
248
249 // Merge params with schema defaults
250 $params += [
251 'condition' => CRM_Utils_Array::value('condition', $pseudoconstant, []),
252 'keyColumn' => CRM_Utils_Array::value('keyColumn', $pseudoconstant),
253 'labelColumn' => CRM_Utils_Array::value('labelColumn', $pseudoconstant),
254 ];
255
256 if ($context == 'abbreviate') {
257 switch ($fieldName) {
258 case 'state_province_id':
259 $params['labelColumn'] = 'abbreviation';
260 break;
261
262 case 'country_id':
263 $params['labelColumn'] = 'iso_code';
264 break;
265
266 default:
267 }
268 }
269
270 // Fetch option group from option_value table
271 if (!empty($pseudoconstant['optionGroupName'])) {
272 if ($context == 'validate') {
273 $params['labelColumn'] = 'name';
274 }
275 if ($context == 'match') {
276 $params['keyColumn'] = 'name';
277 }
278 // Call our generic fn for retrieving from the option_value table
279 $options = CRM_Core_OptionGroup::values(
280 $pseudoconstant['optionGroupName'],
281 $flip,
282 $params['grouping'],
283 $params['localize'],
284 $params['condition'] ? ' AND ' . implode(' AND ', (array) $params['condition']) : NULL,
285 $params['labelColumn'] ? $params['labelColumn'] : 'label',
286 $params['onlyActive'],
287 $params['fresh'],
288 $params['keyColumn'] ? $params['keyColumn'] : 'value',
289 !empty($params['orderColumn']) ? $params['orderColumn'] : 'weight'
290 );
291 CRM_Utils_Hook::fieldOptions($entity, $fieldName, $options, $params);
292 return $options;
293 }
294
295 // Fetch options from other tables
296 if (!empty($pseudoconstant['table'])) {
297 // Normalize params so the serialized cache string will be consistent.
298 CRM_Utils_Array::remove($params, 'flip', 'fresh');
299 ksort($params);
300 $cacheKey = $daoName . $fieldName . serialize($params);
301
302 // Retrieve cached options
303 if (isset(self::$cache[$cacheKey]) && empty($params['fresh'])) {
304 $output = self::$cache[$cacheKey];
305 }
306 else {
307 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($pseudoconstant['table']);
308 if (!class_exists($daoName)) {
309 return FALSE;
310 }
311 // Get list of fields for the option table
312 $dao = new $daoName();
313 $availableFields = array_keys($dao->fieldKeys());
314
315 $select = "SELECT %1 AS id, %2 AS label";
316 $from = "FROM %3";
317 $wheres = [];
318 $order = "ORDER BY %2";
319
320 // Use machine name in certain contexts
321 if ($context == 'validate' || $context == 'match') {
322 $nameField = $context == 'validate' ? 'labelColumn' : 'keyColumn';
323 if (!empty($pseudoconstant['nameColumn'])) {
324 $params[$nameField] = $pseudoconstant['nameColumn'];
325 }
326 elseif (in_array('name', $availableFields)) {
327 $params[$nameField] = 'name';
328 }
329 }
330 // Condition param can be passed as an sql clause string or an array of clauses
331 if (!empty($params['condition'])) {
332 $wheres[] = implode(' AND ', (array) $params['condition']);
333 }
334 // onlyActive param will automatically filter on common flags
335 if (!empty($params['onlyActive'])) {
336 foreach (['is_active' => 1, 'is_deleted' => 0, 'is_test' => 0, 'is_hidden' => 0] as $flag => $val) {
337 if (in_array($flag, $availableFields)) {
338 $wheres[] = "$flag = $val";
339 }
340 }
341 }
342 // Filter domain specific options
343 if (in_array('domain_id', $availableFields)) {
344 $wheres[] = 'domain_id = ' . CRM_Core_Config::domainID();
345 }
346 $queryParams = [
347 1 => [$params['keyColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES],
348 2 => [$params['labelColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES],
349 3 => [$pseudoconstant['table'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES],
350 ];
351 // Add orderColumn param
352 if (!empty($params['orderColumn'])) {
353 $queryParams[4] = [$params['orderColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES];
354 $order = "ORDER BY %4";
355 }
356 // Support no sorting if $params[orderColumn] is FALSE
357 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
358 $order = '';
359 }
360 // Default to 'weight' if that column exists
361 elseif (in_array('weight', $availableFields)) {
362 $order = "ORDER BY weight";
363 }
364
365 $output = [];
366 $query = "$select $from";
367 if ($wheres) {
368 $query .= " WHERE " . implode($wheres, ' AND ');
369 }
370 $query .= ' ' . $order;
371 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
372 while ($dao->fetch()) {
373 $output[$dao->id] = $dao->label;
374 }
375 // Localize results
376 if (!empty($params['localize']) || $pseudoconstant['table'] == 'civicrm_country' || $pseudoconstant['table'] == 'civicrm_state_province') {
377 $I18nParams = [];
378 if (isset($fieldSpec['localize_context'])) {
379 $I18nParams['context'] = $fieldSpec['localize_context'];
380 }
381 $i18n = CRM_Core_I18n::singleton();
382 $i18n->localizeArray($output, $I18nParams);
383 // Maintain sort by label
384 if ($order == "ORDER BY %2") {
385 CRM_Utils_Array::asort($output);
386 }
387 }
388 CRM_Utils_Hook::fieldOptions($entity, $fieldName, $output, $params);
389 self::$cache[$cacheKey] = $output;
390 }
391 return $flip ? array_flip($output) : $output;
392 }
393 }
394
395 // Return "Yes" and "No" for boolean fields
396 elseif (CRM_Utils_Array::value('type', $fieldSpec) === CRM_Utils_Type::T_BOOLEAN) {
397 $output = $context == 'validate' ? [0, 1] : CRM_Core_SelectValues::boolean();
398 CRM_Utils_Hook::fieldOptions($entity, $fieldName, $output, $params);
399 return $flip ? array_flip($output) : $output;
400 }
401 // If we're still here, it's an error. Return FALSE.
402 return FALSE;
403 }
404
405 /**
406 * Fetch the translated label for a field given its key.
407 *
408 * @param string $baoName
409 * @param string $fieldName
410 * @param string|int $key
411 *
412 * TODO: Accept multivalued input?
413 *
414 * @return bool|null|string
415 * FALSE if the given field has no associated option list
416 * NULL if the given key has no corresponding option
417 * String if label is found
418 */
419 public static function getLabel($baoName, $fieldName, $key) {
420 $values = $baoName::buildOptions($fieldName, 'get');
421 if ($values === FALSE) {
422 return FALSE;
423 }
424 return CRM_Utils_Array::value($key, $values);
425 }
426
427 /**
428 * Fetch the machine name for a field given its key.
429 *
430 * @param string $baoName
431 * @param string $fieldName
432 * @param string|int $key
433 *
434 * @return bool|null|string
435 * FALSE if the given field has no associated option list
436 * NULL if the given key has no corresponding option
437 * String if label is found
438 */
439 public static function getName($baoName, $fieldName, $key) {
440 $values = $baoName::buildOptions($fieldName, 'validate');
441 if ($values === FALSE) {
442 return FALSE;
443 }
444 return CRM_Utils_Array::value($key, $values);
445 }
446
447 /**
448 * Fetch the key for a field option given its name.
449 *
450 * @param string $baoName
451 * @param string $fieldName
452 * @param string|int $value
453 *
454 * @return bool|null|string|int
455 * FALSE if the given field has no associated option list
456 * NULL if the given key has no corresponding option
457 * String|Number if key is found
458 */
459 public static function getKey($baoName, $fieldName, $value) {
460 $values = $baoName::buildOptions($fieldName, 'validate');
461 if ($values === FALSE) {
462 return FALSE;
463 }
464 return CRM_Utils_Array::key($value, $values);
465 }
466
467 /**
468 * Lookup the admin page at which a field's option list can be edited
469 * @param $fieldSpec
470 * @return string|null
471 */
472 public static function getOptionEditUrl($fieldSpec) {
473 // If it's an option group, that's easy
474 if (!empty($fieldSpec['pseudoconstant']['optionGroupName'])) {
475 return 'civicrm/admin/options/' . $fieldSpec['pseudoconstant']['optionGroupName'];
476 }
477 // For everything else...
478 elseif (!empty($fieldSpec['pseudoconstant']['table'])) {
479 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($fieldSpec['pseudoconstant']['table']);
480 if (!$daoName) {
481 return NULL;
482 }
483 // We don't have good mapping so have to do a bit of guesswork from the menu
484 list(, $parent, , $child) = explode('_', $daoName);
485 $sql = "SELECT path FROM civicrm_menu
486 WHERE page_callback LIKE '%CRM_Admin_Page_$child%' OR page_callback LIKE '%CRM_{$parent}_Page_$child%'
487 ORDER BY page_callback
488 LIMIT 1";
489 return CRM_Core_Dao::singleValueQuery($sql);
490 }
491 return NULL;
492 }
493
494 /**
495 * @deprecated generic populate method.
496 * All pseudoconstant functions that use this method are also @deprecated
497 *
498 * The static array $var is populated from the db
499 * using the <b>$name DAO</b>.
500 *
501 * Note: any database errors will be trapped by the DAO.
502 *
503 * @param array $var
504 * The associative array we will fill.
505 * @param string $name
506 * The name of the DAO.
507 * @param bool $all
508 * Get all objects. default is to get only active ones.
509 * @param string $retrieve
510 * The field that we are interested in (normally name, differs in some objects).
511 * @param string $filter
512 * The field that we want to filter the result set with.
513 * @param string $condition
514 * The condition that gets passed to the final query as the WHERE clause.
515 *
516 * @param bool $orderby
517 * @param string $key
518 * @param bool $force
519 *
520 * @return array
521 */
522 public static function populate(
523 &$var,
524 $name,
525 $all = FALSE,
526 $retrieve = 'name',
527 $filter = 'is_active',
528 $condition = NULL,
529 $orderby = NULL,
530 $key = 'id',
531 $force = NULL
532 ) {
533 $cacheKey = CRM_Core_BAO_Cache::cleanKey("CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}");
534 $cache = CRM_Utils_Cache::singleton();
535 $var = $cache->get($cacheKey);
536 if ($var !== NULL && empty($force)) {
537 return $var;
538 }
539
540 /* @var CRM_Core_DAO $object */
541 $object = new $name();
542
543 $object->selectAdd();
544 $object->selectAdd("$key, $retrieve");
545 if ($condition) {
546 $object->whereAdd($condition);
547 }
548
549 if (!$orderby) {
550 $object->orderBy($retrieve);
551 }
552 else {
553 $object->orderBy($orderby);
554 }
555
556 if (!$all) {
557 $object->$filter = 1;
558 $aclClauses = array_filter($name::getSelectWhereClause());
559 foreach ($aclClauses as $clause) {
560 $object->whereAdd($clause);
561 }
562 }
563
564 $object->find();
565 $var = [];
566 while ($object->fetch()) {
567 $var[$object->$key] = $object->$retrieve;
568 }
569
570 $cache->set($cacheKey, $var);
571 }
572
573 /**
574 * Flush given pseudoconstant so it can be reread from db.
575 * nex time it's requested.
576 *
577 * @param bool|string $name pseudoconstant to be flushed
578 */
579 public static function flush($name = 'cache') {
580 if (isset(self::$$name)) {
581 self::$$name = NULL;
582 }
583 if ($name == 'cache') {
584 CRM_Core_OptionGroup::flushAll();
585 if (isset(\Civi::$statics[__CLASS__])) {
586 unset(\Civi::$statics[__CLASS__]);
587 }
588 }
589 }
590
591 /**
592 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
593 *
594 * Get all Activty types.
595 *
596 * The static array activityType is returned
597 *
598 *
599 * @return array
600 * array reference of all activity types.
601 */
602 public static function &activityType() {
603 $args = func_get_args();
604 $all = CRM_Utils_Array::value(0, $args, TRUE);
605 $includeCaseActivities = CRM_Utils_Array::value(1, $args, FALSE);
606 $reset = CRM_Utils_Array::value(2, $args, FALSE);
607 $returnColumn = CRM_Utils_Array::value(3, $args, 'label');
608 $includeCampaignActivities = CRM_Utils_Array::value(4, $args, FALSE);
609 $onlyComponentActivities = CRM_Utils_Array::value(5, $args, FALSE);
610 $index = (int) $all . '_' . $returnColumn . '_' . (int) $includeCaseActivities;
611 $index .= '_' . (int) $includeCampaignActivities;
612 $index .= '_' . (int) $onlyComponentActivities;
613
614 if (NULL === self::$activityType) {
615 self::$activityType = [];
616 }
617
618 if (!isset(self::$activityType[$index]) || $reset) {
619 $condition = NULL;
620 if (!$all) {
621 $condition = 'AND filter = 0';
622 }
623 $componentClause = " v.component_id IS NULL";
624 if ($onlyComponentActivities) {
625 $componentClause = " v.component_id IS NOT NULL";
626 }
627
628 $componentIds = [];
629 $compInfo = CRM_Core_Component::getEnabledComponents();
630
631 // build filter for listing activity types only if their
632 // respective components are enabled
633 foreach ($compInfo as $compName => $compObj) {
634 if ($compName == 'CiviCase') {
635 if ($includeCaseActivities) {
636 $componentIds[] = $compObj->componentID;
637 }
638 }
639 elseif ($compName == 'CiviCampaign') {
640 if ($includeCampaignActivities) {
641 $componentIds[] = $compObj->componentID;
642 }
643 }
644 else {
645 $componentIds[] = $compObj->componentID;
646 }
647 }
648
649 if (count($componentIds)) {
650 $componentIds = implode(',', $componentIds);
651 $componentClause = " ($componentClause OR v.component_id IN ($componentIds))";
652 if ($onlyComponentActivities) {
653 $componentClause = " ( v.component_id IN ($componentIds ) )";
654 }
655 }
656 $condition = $condition . ' AND ' . $componentClause;
657
658 self::$activityType[$index] = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
659 }
660 return self::$activityType[$index];
661 }
662
663 /**
664 * Get all the State/Province from database.
665 *
666 * The static array stateProvince is returned, and if it's
667 * called the first time, the <b>State Province DAO</b> is used
668 * to get all the States.
669 *
670 * Note: any database errors will be trapped by the DAO.
671 *
672 *
673 * @param bool|int $id - Optional id to return
674 *
675 * @param bool $limit
676 *
677 * @return array
678 * array reference of all State/Provinces.
679 */
680 public static function &stateProvince($id = FALSE, $limit = TRUE) {
681 if (($id && !CRM_Utils_Array::value($id, self::$stateProvince)) || !self::$stateProvince || !$id) {
682 $whereClause = FALSE;
683 if ($limit) {
684 $countryIsoCodes = self::countryIsoCode();
685 $limitCodes = CRM_Core_BAO_Country::provinceLimit();
686 $limitIds = [];
687 foreach ($limitCodes as $code) {
688 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
689 }
690 if (!empty($limitIds)) {
691 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
692 }
693 else {
694 $whereClause = FALSE;
695 }
696 }
697 self::populate(self::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
698
699 // localise the province names if in an non-en_US locale
700 $tsLocale = CRM_Core_I18n::getLocale();
701 if ($tsLocale != '' and $tsLocale != 'en_US') {
702 $i18n = CRM_Core_I18n::singleton();
703 $i18n->localizeArray(self::$stateProvince, [
704 'context' => 'province',
705 ]);
706 self::$stateProvince = CRM_Utils_Array::asort(self::$stateProvince);
707 }
708 }
709 if ($id) {
710 if (array_key_exists($id, self::$stateProvince)) {
711 return self::$stateProvince[$id];
712 }
713 else {
714 $result = NULL;
715 return $result;
716 }
717 }
718 return self::$stateProvince;
719 }
720
721 /**
722 * Get all the State/Province abbreviations from the database.
723 *
724 * Same as above, except gets the abbreviations instead of the names.
725 *
726 *
727 * @param bool|int $id - Optional id to return
728 *
729 * @param bool $limit
730 *
731 * @return array
732 * array reference of all State/Province abbreviations.
733 */
734 public static function stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
735 if ($id && is_numeric($id)) {
736 if (!array_key_exists($id, (array) self::$stateProvinceAbbreviation)) {
737 $query = "SELECT abbreviation
738 FROM civicrm_state_province
739 WHERE id = %1";
740 $params = [
741 1 => [
742 $id,
743 'Integer',
744 ],
745 ];
746 self::$stateProvinceAbbreviation[$id] = CRM_Core_DAO::singleValueQuery($query, $params);
747 }
748 return self::$stateProvinceAbbreviation[$id];
749 }
750 else {
751 $whereClause = FALSE;
752
753 if ($limit) {
754 $countryIsoCodes = self::countryIsoCode();
755 $limitCodes = CRM_Core_BAO_Country::provinceLimit();
756 $limitIds = [];
757 foreach ($limitCodes as $code) {
758 $tmpArray = array_keys($countryIsoCodes, $code);
759
760 if (!empty($tmpArray)) {
761 $limitIds[] = array_shift($tmpArray);
762 }
763 }
764 if (!empty($limitIds)) {
765 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
766 }
767 }
768 self::populate(self::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
769 }
770
771 return self::$stateProvinceAbbreviation;
772 }
773
774 /**
775 * Get all the State/Province abbreviations from the database for the specified country.
776 *
777 * @param int $countryID
778 *
779 * @return array
780 * array of all State/Province abbreviations for the given country.
781 */
782 public static function stateProvinceAbbreviationForCountry($countryID) {
783 if (!isset(\Civi::$statics[__CLASS__]['stateProvinceAbbreviationForCountry'][$countryID])) {
784 \Civi::$statics[__CLASS__]['stateProvinceAbbreviationForCountry'][$countryID] = [];
785 }
786 self::populate(\Civi::$statics[__CLASS__]['stateProvinceAbbreviationForCountry'][$countryID], 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', "country_id = " . (int) $countryID, 'abbreviation');
787 return \Civi::$statics[__CLASS__]['stateProvinceAbbreviationForCountry'][$countryID];
788 }
789
790 /**
791 * Get all the State/Province abbreviations from the database for the default country.
792 *
793 * @return array
794 * array of all State/Province abbreviations for the given country.
795 */
796 public static function stateProvinceAbbreviationForDefaultCountry() {
797 return CRM_Core_PseudoConstant::stateProvinceAbbreviationForCountry(Civi::settings()->get('defaultContactCountry'));
798 }
799
800 /**
801 * Get all the countries from database.
802 *
803 * The static array country is returned, and if it's
804 * called the first time, the <b>Country DAO</b> is used
805 * to get all the countries.
806 *
807 * Note: any database errors will be trapped by the DAO.
808 *
809 *
810 * @param bool|int $id - Optional id to return
811 *
812 * @param bool $applyLimit
813 *
814 * @return array|null
815 * array reference of all countries.
816 */
817 public static function country($id = FALSE, $applyLimit = TRUE) {
818 if (($id && !CRM_Utils_Array::value($id, self::$country)) || !self::$country || !$id) {
819
820 $config = CRM_Core_Config::singleton();
821 $limitCodes = [];
822
823 if ($applyLimit) {
824 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
825 // (ensuring it's a subset of the legal values)
826 // K/P: We need to fix this, i dont think it works with new setting files
827 $limitCodes = CRM_Core_BAO_Country::countryLimit();
828 if (!is_array($limitCodes)) {
829 $limitCodes = [
830 $config->countryLimit => 1,
831 ];
832 }
833
834 $limitCodes = array_intersect(self::countryIsoCode(), $limitCodes);
835 }
836
837 if (count($limitCodes)) {
838 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
839 }
840 else {
841 $whereClause = NULL;
842 }
843
844 self::populate(self::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
845
846 // if default country is set, percolate it to the top
847 if ($config->defaultContactCountry()) {
848 $countryIsoCodes = self::countryIsoCode();
849 $defaultID = array_search($config->defaultContactCountry(), $countryIsoCodes);
850 if ($defaultID !== FALSE) {
851 $default[$defaultID] = CRM_Utils_Array::value($defaultID, self::$country);
852 self::$country = $default + self::$country;
853 }
854 }
855
856 // localise the country names if in an non-en_US locale
857 $tsLocale = CRM_Core_I18n::getLocale();
858 if ($tsLocale != '' and $tsLocale != 'en_US') {
859 $i18n = CRM_Core_I18n::singleton();
860 $i18n->localizeArray(self::$country, [
861 'context' => 'country',
862 ]);
863 self::$country = CRM_Utils_Array::asort(self::$country);
864 }
865 }
866 if ($id) {
867 if (array_key_exists($id, self::$country)) {
868 return self::$country[$id];
869 }
870 else {
871 return NULL;
872 }
873 }
874 return self::$country;
875 }
876
877 /**
878 * Get all the country ISO Code abbreviations from the database.
879 *
880 * The static array countryIsoCode is returned, and if it's
881 * called the first time, the <b>Country DAO</b> is used
882 * to get all the countries' ISO codes.
883 *
884 * Note: any database errors will be trapped by the DAO.
885 *
886 *
887 * @param bool $id
888 *
889 * @return array
890 * array reference of all country ISO codes.
891 */
892 public static function &countryIsoCode($id = FALSE) {
893 if (!self::$countryIsoCode) {
894 self::populate(self::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
895 }
896 if ($id) {
897 if (array_key_exists($id, self::$countryIsoCode)) {
898 return self::$countryIsoCode[$id];
899 }
900 else {
901 return CRM_Core_DAO::$_nullObject;
902 }
903 }
904 return self::$countryIsoCode;
905 }
906
907 /**
908 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
909 *
910 * Get all groups from database
911 *
912 * The static array group is returned, and if it's
913 * called the first time, the <b>Group DAO</b> is used
914 * to get all the groups.
915 *
916 * Note: any database errors will be trapped by the DAO.
917 *
918 * @param string $groupType
919 * Type of group(Access/Mailing).
920 * @param bool $excludeHidden
921 * Exclude hidden groups.
922 *
923 *
924 * @return array
925 * array reference of all groups.
926 */
927 public static function allGroup($groupType = NULL, $excludeHidden = TRUE) {
928 if ($groupType === 'validate') {
929 // validate gets passed through from getoptions. Handle in the deprecated
930 // fn rather than change the new pattern.
931 $groupType = NULL;
932 }
933 $condition = CRM_Contact_BAO_Group::groupTypeCondition($groupType, $excludeHidden);
934 $groupKey = ($groupType ? $groupType : 'null') . !empty($excludeHidden);
935
936 if (!isset(Civi::$statics[__CLASS__]['groups']['allGroup'][$groupKey])) {
937 self::populate(Civi::$statics[__CLASS__]['groups']['allGroup'][$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
938 }
939 return Civi::$statics[__CLASS__]['groups']['allGroup'][$groupKey];
940 }
941
942 /**
943 * Get all permissioned groups from database.
944 *
945 * The static array group is returned, and if it's
946 * called the first time, the <b>Group DAO</b> is used
947 * to get all the groups.
948 *
949 * Note: any database errors will be trapped by the DAO.
950 *
951 * @param string $groupType
952 * Type of group(Access/Mailing).
953 * @param bool $excludeHidden
954 * Exclude hidden groups.
955 *
956 *
957 * @return array
958 * array reference of all groups.
959 */
960 public static function group($groupType = NULL, $excludeHidden = TRUE) {
961 return CRM_Core_Permission::group($groupType, $excludeHidden);
962 }
963
964 /**
965 * Fetch groups in a nested format suitable for use in select form element.
966 * @param bool $checkPermissions
967 * @param string|null $groupType
968 * @param bool $excludeHidden
969 * @return array
970 */
971 public static function nestedGroup($checkPermissions = TRUE, $groupType = NULL, $excludeHidden = TRUE) {
972 $groups = $checkPermissions ? self::group($groupType, $excludeHidden) : self::allGroup($groupType, $excludeHidden);
973 return CRM_Contact_BAO_Group::getGroupsHierarchy($groups, NULL, '&nbsp;&nbsp;', TRUE);
974 }
975
976 /**
977 * Get all permissioned groups from database.
978 *
979 * The static array group is returned, and if it's
980 * called the first time, the <b>Group DAO</b> is used
981 * to get all the groups.
982 *
983 * Note: any database errors will be trapped by the DAO.
984 *
985 *
986 * @param bool $onlyPublic
987 * @param null $groupType
988 * @param bool $excludeHidden
989 *
990 * @return array
991 * array reference of all groups.
992 */
993 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
994 if (!self::$staticGroup) {
995 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
996 if ($onlyPublic) {
997 $condition .= " AND visibility != 'User and User Admin Only'";
998 }
999
1000 if ($groupType) {
1001 $condition .= ' AND ' . CRM_Contact_BAO_Group::groupTypeCondition($groupType);
1002 }
1003
1004 if ($excludeHidden) {
1005 $condition .= ' AND is_hidden != 1 ';
1006 }
1007
1008 self::populate(self::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
1009 }
1010
1011 return self::$staticGroup;
1012 }
1013
1014 /**
1015 * Get all Relationship Types from database.
1016 *
1017 * The static array group is returned, and if it's
1018 * called the first time, the <b>RelationshipType DAO</b> is used
1019 * to get all the relationship types.
1020 *
1021 * Note: any database errors will be trapped by the DAO.
1022 *
1023 * @param string $valueColumnName
1024 * Db column name/label.
1025 * @param bool $reset
1026 * Reset relationship types if true.
1027 * @param bool $isActive
1028 * Filter by is_active. NULL to disable.
1029 *
1030 * @return array
1031 * array reference of all relationship types.
1032 */
1033 public static function &relationshipType($valueColumnName = 'label', $reset = FALSE, $isActive = 1) {
1034 $cacheKey = $valueColumnName . '::' . $isActive;
1035 if (!CRM_Utils_Array::value($cacheKey, self::$relationshipType) || $reset) {
1036 self::$relationshipType[$cacheKey] = [];
1037
1038 //now we have name/label columns CRM-3336
1039 $column_a_b = "{$valueColumnName}_a_b";
1040 $column_b_a = "{$valueColumnName}_b_a";
1041
1042 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1043 $relationshipTypeDAO->selectAdd();
1044 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1045 if ($isActive !== NULL) {
1046 $relationshipTypeDAO->is_active = $isActive;
1047 }
1048 $relationshipTypeDAO->find();
1049 while ($relationshipTypeDAO->fetch()) {
1050
1051 self::$relationshipType[$cacheKey][$relationshipTypeDAO->id] = [
1052 'id' => $relationshipTypeDAO->id,
1053 $column_a_b => $relationshipTypeDAO->$column_a_b,
1054 $column_b_a => $relationshipTypeDAO->$column_b_a,
1055 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1056 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1057 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1058 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1059 ];
1060 }
1061 }
1062
1063 return self::$relationshipType[$cacheKey];
1064 }
1065
1066 /**
1067 * Get all the ISO 4217 currency codes
1068 *
1069 * so far, we use this for validation only, so there's no point of putting this into the database
1070 *
1071 *
1072 * @return array
1073 * array reference of all currency codes
1074 */
1075 public static function &currencyCode() {
1076 if (!self::$currencyCode) {
1077
1078 $query = "SELECT name FROM civicrm_currency";
1079 $dao = CRM_Core_DAO::executeQuery($query);
1080 $currencyCode = [];
1081 while ($dao->fetch()) {
1082 self::$currencyCode[] = $dao->name;
1083 }
1084 }
1085 return self::$currencyCode;
1086 }
1087
1088 /**
1089 * Get all the County from database.
1090 *
1091 * The static array county is returned, and if it's
1092 * called the first time, the <b>County DAO</b> is used
1093 * to get all the Counties.
1094 *
1095 * Note: any database errors will be trapped by the DAO.
1096 *
1097 *
1098 * @param bool|int $id - Optional id to return
1099 *
1100 * @return array
1101 * array reference of all Counties
1102 */
1103 public static function &county($id = FALSE) {
1104 if (!self::$county) {
1105
1106 $config = CRM_Core_Config::singleton();
1107 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1108 self::populate(self::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1109 }
1110 if ($id) {
1111 if (array_key_exists($id, self::$county)) {
1112 return self::$county[$id];
1113 }
1114 else {
1115 return CRM_Core_DAO::$_nullObject;
1116 }
1117 }
1118 return self::$county;
1119 }
1120
1121 /**
1122 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1123 * Get all active payment processors
1124 *
1125 * The static array paymentProcessor is returned
1126 *
1127 *
1128 * @param bool $all
1129 * Get payment processors - default is to get only active ones.
1130 * @param bool $test
1131 * Get test payment processors.
1132 *
1133 * @param null $additionalCond
1134 *
1135 * @return array
1136 * array of all payment processors
1137 */
1138 public static function paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1139 $condition = "is_test = ";
1140 $condition .= ($test) ? '1' : '0';
1141
1142 if ($additionalCond) {
1143 $condition .= " AND ( $additionalCond ) ";
1144 }
1145
1146 // CRM-7178. Make sure we only include payment processors valid in this
1147 // domain
1148 $condition .= " AND domain_id = " . CRM_Core_Config::domainID();
1149
1150 $cacheKey = $condition . '_' . (int) $all;
1151 if (!isset(self::$paymentProcessor[$cacheKey])) {
1152 self::populate(self::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1153 }
1154
1155 return self::$paymentProcessor[$cacheKey];
1156 }
1157
1158 /**
1159 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1160 *
1161 * The static array paymentProcessorType is returned
1162 *
1163 *
1164 * @param bool $all
1165 * Get payment processors - default is to get only active ones.
1166 *
1167 * @param int $id
1168 * @param string $return
1169 *
1170 * @return array
1171 * array of all payment processor types
1172 */
1173 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1174 $cacheKey = $id . '_' . $return;
1175 if (empty(self::$paymentProcessorType[$cacheKey])) {
1176 self::populate(self::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1177 }
1178 if ($id && CRM_Utils_Array::value($id, self::$paymentProcessorType[$cacheKey])) {
1179 return self::$paymentProcessorType[$cacheKey][$id];
1180 }
1181 return self::$paymentProcessorType[$cacheKey];
1182 }
1183
1184 /**
1185 * Get all the World Regions from Database.
1186 *
1187 *
1188 * @param bool $id
1189 *
1190 * @return array
1191 * array reference of all World Regions
1192 */
1193 public static function &worldRegion($id = FALSE) {
1194 if (!self::$worldRegions) {
1195 self::populate(self::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1196 }
1197
1198 if ($id) {
1199 if (array_key_exists($id, self::$worldRegions)) {
1200 return self::$worldRegions[$id];
1201 }
1202 else {
1203 return CRM_Core_DAO::$_nullObject;
1204 }
1205 }
1206
1207 return self::$worldRegions;
1208 }
1209
1210 /**
1211 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1212 *
1213 * Get all Activity Statuses.
1214 *
1215 * The static array activityStatus is returned
1216 *
1217 *
1218 * @param string $column
1219 *
1220 * @return array
1221 * array reference of all activity statuses
1222 */
1223 public static function &activityStatus($column = 'label') {
1224 if (NULL === self::$activityStatus) {
1225 self::$activityStatus = [];
1226 }
1227 if (!array_key_exists($column, self::$activityStatus)) {
1228 self::$activityStatus[$column] = [];
1229
1230 self::$activityStatus[$column] = CRM_Core_OptionGroup::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1231 }
1232
1233 return self::$activityStatus[$column];
1234 }
1235
1236 /**
1237 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1238 *
1239 * Get all Visibility levels.
1240 *
1241 * The static array visibility is returned
1242 *
1243 *
1244 * @param string $column
1245 *
1246 * @return array
1247 * array reference of all Visibility levels.
1248 */
1249 public static function &visibility($column = 'label') {
1250 if (!isset(self::$visibility)) {
1251 self::$visibility = [];
1252 }
1253
1254 if (!isset(self::$visibility[$column])) {
1255 self::$visibility[$column] = CRM_Core_OptionGroup::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1256 }
1257
1258 return self::$visibility[$column];
1259 }
1260
1261 /**
1262 * @param int $countryID
1263 * @param string $field
1264 *
1265 * @return array
1266 */
1267 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1268 static $_cache = NULL;
1269
1270 $cacheKey = "{$countryID}_{$field}";
1271 if (!$_cache) {
1272 $_cache = [];
1273 }
1274
1275 if (!empty($_cache[$cacheKey])) {
1276 return $_cache[$cacheKey];
1277 }
1278
1279 $query = "
1280 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1281 FROM civicrm_state_province
1282 WHERE country_id = %1
1283 ORDER BY name";
1284 $params = [
1285 1 => [
1286 $countryID,
1287 'Integer',
1288 ],
1289 ];
1290
1291 $dao = CRM_Core_DAO::executeQuery($query, $params);
1292
1293 $result = [];
1294 while ($dao->fetch()) {
1295 $result[$dao->id] = $dao->name;
1296 }
1297
1298 // localise the stateProvince names if in an non-en_US locale
1299 $config = CRM_Core_Config::singleton();
1300 $tsLocale = CRM_Core_I18n::getLocale();
1301 if ($tsLocale != '' and $tsLocale != 'en_US') {
1302 $i18n = CRM_Core_I18n::singleton();
1303 $i18n->localizeArray($result, [
1304 'context' => 'province',
1305 ]);
1306 $result = CRM_Utils_Array::asort($result);
1307 }
1308
1309 $_cache[$cacheKey] = $result;
1310
1311 CRM_Utils_Hook::buildStateProvinceForCountry($countryID, $result);
1312
1313 return $result;
1314 }
1315
1316 /**
1317 * @param int $stateID
1318 *
1319 * @return array
1320 */
1321 public static function &countyForState($stateID) {
1322 if (is_array($stateID)) {
1323 $states = implode(", ", $stateID);
1324 $query = "
1325 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1326 FROM civicrm_county
1327 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1328 WHERE civicrm_county.state_province_id in ( $states )
1329 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1330
1331 $dao = CRM_Core_DAO::executeQuery($query);
1332
1333 $result = [];
1334 while ($dao->fetch()) {
1335 $result[$dao->id] = $dao->abbreviation . ': ' . $dao->name;
1336 }
1337 }
1338 else {
1339
1340 static $_cache = NULL;
1341
1342 $cacheKey = "{$stateID}_name";
1343 if (!$_cache) {
1344 $_cache = [];
1345 }
1346
1347 if (!empty($_cache[$cacheKey])) {
1348 return $_cache[$cacheKey];
1349 }
1350
1351 $query = "
1352 SELECT civicrm_county.name name, civicrm_county.id id
1353 FROM civicrm_county
1354 WHERE state_province_id = %1
1355 ORDER BY name";
1356 $params = [
1357 1 => [
1358 $stateID,
1359 'Integer',
1360 ],
1361 ];
1362
1363 $dao = CRM_Core_DAO::executeQuery($query, $params);
1364
1365 $result = [];
1366 while ($dao->fetch()) {
1367 $result[$dao->id] = $dao->name;
1368 }
1369 }
1370
1371 return $result;
1372 }
1373
1374 /**
1375 * Given a state ID return the country ID, this allows
1376 * us to populate forms and values for downstream code
1377 *
1378 * @param int $stateID
1379 *
1380 * @return int|null
1381 * the country id that the state belongs to
1382 */
1383 public static function countryIDForStateID($stateID) {
1384 if (empty($stateID)) {
1385 return NULL;
1386 }
1387
1388 $query = "
1389 SELECT country_id
1390 FROM civicrm_state_province
1391 WHERE id = %1
1392 ";
1393 $params = [1 => [$stateID, 'Integer']];
1394
1395 return CRM_Core_DAO::singleValueQuery($query, $params);
1396 }
1397
1398 /**
1399 * Get all types of Greetings.
1400 *
1401 * The static array of greeting is returned
1402 *
1403 *
1404 * @param $filter
1405 * Get All Email Greetings - default is to get only active ones.
1406 *
1407 * @param string $columnName
1408 *
1409 * @return array
1410 * array reference of all greetings.
1411 */
1412 public static function greeting($filter, $columnName = 'label') {
1413 if (!isset(Civi::$statics[__CLASS__]['greeting'])) {
1414 Civi::$statics[__CLASS__]['greeting'] = [];
1415 }
1416
1417 $index = $filter['greeting_type'] . '_' . $columnName;
1418
1419 // also add contactType to the array
1420 $contactType = CRM_Utils_Array::value('contact_type', $filter);
1421 if ($contactType) {
1422 $index .= '_' . $contactType;
1423 }
1424
1425 if (!CRM_Utils_Array::value($index, Civi::$statics[__CLASS__]['greeting'])) {
1426 $filterCondition = NULL;
1427 if ($contactType) {
1428 $filterVal = 'v.filter =';
1429 switch ($contactType) {
1430 case 'Individual':
1431 $filterVal .= "1";
1432 break;
1433
1434 case 'Household':
1435 $filterVal .= "2";
1436 break;
1437
1438 case 'Organization':
1439 $filterVal .= "3";
1440 break;
1441 }
1442 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1443 }
1444
1445 Civi::$statics[__CLASS__]['greeting'][$index] = CRM_Core_OptionGroup::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1446 }
1447
1448 return Civi::$statics[__CLASS__]['greeting'][$index];
1449 }
1450
1451 /**
1452 * Get all extensions.
1453 *
1454 * The static array extensions
1455 *
1456 * FIXME: This is called by civix but not by any core code. We
1457 * should provide an API call which civix can use instead.
1458 *
1459 *
1460 * @return array
1461 * array($fullyQualifiedName => $label) list of extensions
1462 */
1463 public static function &getExtensions() {
1464 if (!self::$extensions) {
1465 self::$extensions = [];
1466 $sql = '
1467 SELECT full_name, label
1468 FROM civicrm_extension
1469 WHERE is_active = 1
1470 ';
1471 $dao = CRM_Core_DAO::executeQuery($sql);
1472 while ($dao->fetch()) {
1473 self::$extensions[$dao->full_name] = $dao->label;
1474 }
1475 }
1476
1477 return self::$extensions;
1478 }
1479
1480 /**
1481 * Get all options values.
1482 *
1483 * The static array option values is returned
1484 *
1485 *
1486 * @param bool $optionGroupName
1487 * Get All Option Group values- default is to get only active ones.
1488 *
1489 * @param int $id
1490 * @param null $condition
1491 *
1492 * @return array
1493 * array reference of all Option Group Name
1494 */
1495 public static function accountOptionValues($optionGroupName, $id = NULL, $condition = NULL) {
1496 $cacheKey = $optionGroupName . '_' . $condition;
1497 if (empty(self::$accountOptionValues[$cacheKey])) {
1498 self::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup::values($optionGroupName, FALSE, FALSE, FALSE, $condition);
1499 }
1500 if ($id) {
1501 return CRM_Utils_Array::value($id, self::$accountOptionValues[$cacheKey]);
1502 }
1503
1504 return self::$accountOptionValues[$cacheKey];
1505 }
1506
1507 /**
1508 * Fetch the list of active extensions of type 'module'
1509 *
1510 * @param bool $fresh
1511 * Whether to forcibly reload extensions list from canonical store.
1512 *
1513 * @return array
1514 * array(array('prefix' => $, 'file' => $))
1515 */
1516 public static function getModuleExtensions($fresh = FALSE) {
1517 return CRM_Extension_System::singleton()->getMapper()->getActiveModuleFiles($fresh);
1518 }
1519
1520 /**
1521 * Get all tax rates.
1522 *
1523 * The static array tax rates is returned
1524 *
1525 * @return array
1526 * array list of tax rates with the financial type
1527 */
1528 public static function getTaxRates() {
1529 if (!isset(Civi::$statics[__CLASS__]['taxRates'])) {
1530 Civi::$statics[__CLASS__]['taxRates'] = [];
1531 $option = civicrm_api3('option_value', 'get', [
1532 'sequential' => 1,
1533 'option_group_id' => 'account_relationship',
1534 'name' => 'Sales Tax Account is',
1535 ]);
1536 $value = [];
1537 if ($option['count'] !== 0) {
1538 if ($option['count'] > 1) {
1539 foreach ($option['values'] as $opt) {
1540 $value[] = $opt['value'];
1541 }
1542 }
1543 else {
1544 $value[] = $option['values'][0]['value'];
1545 }
1546 $where = 'AND efa.account_relationship IN (' . implode(', ', $value) . ' )';
1547 }
1548 else {
1549 $where = '';
1550 }
1551 $sql = "
1552 SELECT fa.tax_rate, efa.entity_id
1553 FROM civicrm_entity_financial_account efa
1554 INNER JOIN civicrm_financial_account fa ON fa.id = efa.financial_account_id
1555 WHERE efa.entity_table = 'civicrm_financial_type'
1556 {$where}
1557 AND fa.is_active = 1";
1558 $dao = CRM_Core_DAO::executeQuery($sql);
1559 while ($dao->fetch()) {
1560 Civi::$statics[__CLASS__]['taxRates'][$dao->entity_id] = $dao->tax_rate;
1561 }
1562 }
1563
1564 return Civi::$statics[__CLASS__]['taxRates'];
1565 }
1566
1567 /**
1568 * Get participant status class options.
1569 *
1570 * @return array
1571 */
1572 public static function emailOnHoldOptions() {
1573 return [
1574 '0' => ts('No'),
1575 '1' => ts('On Hold Bounce'),
1576 '2' => ts('On Hold Opt Out'),
1577 ];
1578 }
1579
1580 }