Merge pull request #10615 from mepps/CRM-20828
[civicrm-core.git] / CRM / Core / PseudoConstant.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
58 *
59 * activity type
60 * @var array
61 */
62 private static $activityType;
63
64 /**
65 * States, provinces
66 * @var array
67 */
68 private static $stateProvince;
69
70 /**
71 * Counties.
72 * @var array
73 */
74 private static $county;
75
76 /**
77 * States/provinces abbreviations
78 * @var array
79 */
80 private static $stateProvinceAbbreviation = array();
81
82 /**
83 * Country.
84 * @var array
85 */
86 private static $country;
87
88 /**
89 * CountryIsoCode.
90 * @var array
91 */
92 private static $countryIsoCode;
93
94 /**
95 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
96 *
97 * group
98 * @var array
99 */
100 private static $group;
101
102 /**
103 * RelationshipType
104 * @var array
105 */
106 private static $relationshipType;
107
108 /**
109 * Civicrm groups that are not smart groups
110 * @var array
111 */
112 private static $staticGroup;
113
114 /**
115 * Currency codes
116 * @var array
117 */
118 private static $currencyCode;
119
120 /**
121 * Payment processor
122 * @var array
123 */
124 private static $paymentProcessor;
125
126 /**
127 * Payment processor types
128 * @var array
129 */
130 private static $paymentProcessorType;
131
132 /**
133 * World Region
134 * @var array
135 */
136 private static $worldRegions;
137
138 /**
139 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
140 *
141 * activity status
142 * @var array
143 */
144 private static $activityStatus;
145
146 /**
147 * Visibility
148 * @var array
149 */
150 private static $visibility;
151
152 /**
153 * Greetings
154 * @var array
155 */
156 private static $greeting;
157
158 /**
159 * Default Greetings
160 * @var array
161 */
162 private static $greetingDefaults;
163
164 /**
165 * Extensions of type module
166 * @var array
167 */
168 private static $extensions;
169
170 /**
171 * Financial Account Type
172 * @var array
173 */
174 private static $accountOptionValues;
175
176 /**
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
180 *
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.
185 *
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
201 *
202 * @return array|bool
203 * array on success, FALSE on error.
204 *
205 */
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
210 $params += array(
211 'grouping' => FALSE,
212 'localize' => FALSE,
213 'onlyActive' => ($context == 'validate' || $context == 'get') ? FALSE : TRUE,
214 'fresh' => FALSE,
215 'context' => $context,
216 );
217 $entity = CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getCanonicalClassName($daoName));
218
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);
226 }
227 $customField->free();
228 return $options;
229 }
230
231 // Core field: load schema
232 $dao = new $daoName();
233 $fieldSpec = $dao->getFieldSpec($fieldName);
234 $dao->free();
235
236 // Ensure we have the canonical name for this field
237 $fieldName = CRM_Utils_Array::value('name', $fieldSpec, $fieldName);
238
239 // Return false if field doesn't exist.
240 if (empty($fieldSpec)) {
241 return FALSE;
242 }
243
244 elseif (!empty($fieldSpec['pseudoconstant'])) {
245 $pseudoconstant = $fieldSpec['pseudoconstant'];
246
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;
253 }
254
255 // Merge params with schema defaults
256 $params += array(
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),
260 );
261
262 if ($context == 'abbreviate') {
263 switch ($fieldName) {
264 case 'state_province_id':
265 $params['labelColumn'] = 'abbreviation';
266 break;
267
268 case 'country_id':
269 $params['labelColumn'] = 'iso_code';
270 break;
271
272 default:
273 }
274 }
275
276 // Fetch option group from option_value table
277 if (!empty($pseudoconstant['optionGroupName'])) {
278 if ($context == 'validate') {
279 $params['labelColumn'] = 'name';
280 }
281 if ($context == 'match') {
282 $params['keyColumn'] = 'name';
283 }
284 // Call our generic fn for retrieving from the option_value table
285 $options = CRM_Core_OptionGroup::values(
286 $pseudoconstant['optionGroupName'],
287 $flip,
288 $params['grouping'],
289 $params['localize'],
290 $params['condition'] ? ' AND ' . implode(' AND ', (array) $params['condition']) : NULL,
291 $params['labelColumn'] ? $params['labelColumn'] : 'label',
292 $params['onlyActive'],
293 $params['fresh'],
294 $params['keyColumn'] ? $params['keyColumn'] : 'value',
295 !empty($params['orderColumn']) ? $params['orderColumn'] : 'weight'
296 );
297 CRM_Utils_Hook::fieldOptions($entity, $fieldName, $options, $params);
298 return $options;
299 }
300
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');
305 ksort($params);
306 $cacheKey = $daoName . $fieldName . serialize($params);
307
308 // Retrieve cached options
309 if (isset(self::$cache[$cacheKey]) && empty($params['fresh'])) {
310 $output = self::$cache[$cacheKey];
311 }
312 else {
313 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($pseudoconstant['table']);
314 if (!class_exists($daoName)) {
315 return FALSE;
316 }
317 // Get list of fields for the option table
318 $dao = new $daoName();
319 $availableFields = array_keys($dao->fieldKeys());
320 $dao->free();
321
322 $select = "SELECT %1 AS id, %2 AS label";
323 $from = "FROM %3";
324 $wheres = array();
325 $order = "ORDER BY %2";
326
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'];
332 }
333 elseif (in_array('name', $availableFields)) {
334 $params[$nameField] = 'name';
335 }
336 }
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']);
340 }
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";
346 }
347 }
348 }
349 // Filter domain specific options
350 if (in_array('domain_id', $availableFields)) {
351 $wheres[] = 'domain_id = ' . CRM_Core_Config::domainID();
352 }
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),
357 );
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";
362 }
363 // Support no sorting if $params[orderColumn] is FALSE
364 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
365 $order = '';
366 }
367 // Default to 'weight' if that column exists
368 elseif (in_array('weight', $availableFields)) {
369 $order = "ORDER BY weight";
370 }
371
372 $output = array();
373 $query = "$select $from";
374 if ($wheres) {
375 $query .= " WHERE " . implode($wheres, ' AND ');
376 }
377 $query .= ' ' . $order;
378 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
379 while ($dao->fetch()) {
380 $output[$dao->id] = $dao->label;
381 }
382 $dao->free();
383 // Localize results
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';
388 }
389 if ($pseudoconstant['table'] == 'civicrm_state_province') {
390 $I18nParams['context'] = 'province';
391 }
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);
397 }
398 }
399 CRM_Utils_Hook::fieldOptions($entity, $fieldName, $output, $params);
400 self::$cache[$cacheKey] = $output;
401 }
402 return $flip ? array_flip($output) : $output;
403 }
404 }
405
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;
411 }
412 // If we're still here, it's an error. Return FALSE.
413 return FALSE;
414 }
415
416 /**
417 * Fetch the translated label for a field given its key.
418 *
419 * @param string $baoName
420 * @param string $fieldName
421 * @param string|Int $key
422 *
423 * TODO: Accept multivalued input?
424 *
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
429 */
430 public static function getLabel($baoName, $fieldName, $key) {
431 $values = $baoName::buildOptions($fieldName, 'get');
432 if ($values === FALSE) {
433 return FALSE;
434 }
435 return CRM_Utils_Array::value($key, $values);
436 }
437
438 /**
439 * Fetch the machine name for a field given its key.
440 *
441 * @param string $baoName
442 * @param string $fieldName
443 * @param string|Int $key
444 *
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
449 */
450 public static function getName($baoName, $fieldName, $key) {
451 $values = $baoName::buildOptions($fieldName, 'validate');
452 if ($values === FALSE) {
453 return FALSE;
454 }
455 return CRM_Utils_Array::value($key, $values);
456 }
457
458 /**
459 * Fetch the key for a field option given its name.
460 *
461 * @param string $baoName
462 * @param string $fieldName
463 * @param string|Int $value
464 *
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
469 */
470 public static function getKey($baoName, $fieldName, $value) {
471 $values = $baoName::buildOptions($fieldName, 'validate');
472 if ($values === FALSE) {
473 return FALSE;
474 }
475 return CRM_Utils_Array::key($value, $values);
476 }
477
478 /**
479 * Lookup the admin page at which a field's option list can be edited
480 * @param $fieldSpec
481 * @return string|null
482 */
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'];
487 }
488 // For everything else...
489 elseif (!empty($fieldSpec['pseudoconstant']['table'])) {
490 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($fieldSpec['pseudoconstant']['table']);
491 if (!$daoName) {
492 return NULL;
493 }
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
499 LIMIT 1";
500 return CRM_Core_Dao::singleValueQuery($sql);
501 }
502 return NULL;
503 }
504
505 /**
506 * DEPRECATED generic populate method.
507 * All pseudoconstant functions that use this method are also @deprecated
508 *
509 * The static array $var is populated from the db
510 * using the <b>$name DAO</b>.
511 *
512 * Note: any database errors will be trapped by the DAO.
513 *
514 * @param array $var
515 * The associative array we will fill.
516 * @param string $name
517 * The name of the DAO.
518 * @param bool $all
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.
526 *
527 * @param bool $orderby
528 * @param string $key
529 * @param bool $force
530 *
531 * @return array
532 */
533 public static function populate(
534 &$var,
535 $name,
536 $all = FALSE,
537 $retrieve = 'name',
538 $filter = 'is_active',
539 $condition = NULL,
540 $orderby = NULL,
541 $key = 'id',
542 $force = NULL
543 ) {
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)) {
548 return $var;
549 }
550
551 /* @var CRM_Core_DAO $object */
552 $object = new $name();
553
554 $object->selectAdd();
555 $object->selectAdd("$key, $retrieve");
556 if ($condition) {
557 $object->whereAdd($condition);
558 }
559
560 if (!$orderby) {
561 $object->orderBy($retrieve);
562 }
563 else {
564 $object->orderBy($orderby);
565 }
566
567 if (!$all) {
568 $object->$filter = 1;
569 $aclClauses = array_filter($name::getSelectWhereClause());
570 foreach ($aclClauses as $clause) {
571 $object->whereAdd($clause);
572 }
573 }
574
575 $object->find();
576 $var = array();
577 while ($object->fetch()) {
578 $var[$object->$key] = $object->$retrieve;
579 }
580
581 $cache->set($cacheKey, $var);
582 }
583
584 /**
585 * Flush given pseudoconstant so it can be reread from db.
586 * nex time it's requested.
587 *
588 *
589 * @param bool|string $name pseudoconstant to be flushed
590 */
591 public static function flush($name = 'cache') {
592 if (isset(self::$$name)) {
593 self::$$name = NULL;
594 }
595 if ($name == 'cache') {
596 CRM_Core_OptionGroup::flushAll();
597 }
598 }
599
600 /**
601 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
602 *
603 * Get all Activty types.
604 *
605 * The static array activityType is returned
606 *
607 *
608 * @return array
609 * array reference of all activity types.
610 */
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;
622
623 if (NULL === self::$activityType) {
624 self::$activityType = array();
625 }
626
627 if (!isset(self::$activityType[$index]) || $reset) {
628 $condition = NULL;
629 if (!$all) {
630 $condition = 'AND filter = 0';
631 }
632 $componentClause = " v.component_id IS NULL";
633 if ($onlyComponentActivities) {
634 $componentClause = " v.component_id IS NOT NULL";
635 }
636
637 $componentIds = array();
638 $compInfo = CRM_Core_Component::getEnabledComponents();
639
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;
646 }
647 }
648 elseif ($compName == 'CiviCampaign') {
649 if ($includeCampaignActivities) {
650 $componentIds[] = $compObj->componentID;
651 }
652 }
653 else {
654 $componentIds[] = $compObj->componentID;
655 }
656 }
657
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 ) )";
663 }
664 }
665 $condition = $condition . ' AND ' . $componentClause;
666
667 self::$activityType[$index] = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
668 }
669 return self::$activityType[$index];
670 }
671
672 /**
673 * Get all the State/Province from database.
674 *
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.
678 *
679 * Note: any database errors will be trapped by the DAO.
680 *
681 *
682 * @param bool|int $id - Optional id to return
683 *
684 * @param bool $limit
685 *
686 * @return array
687 * array reference of all State/Provinces.
688 */
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;
692 if ($limit) {
693 $countryIsoCodes = self::countryIsoCode();
694 $limitCodes = CRM_Core_BAO_Country::provinceLimit();
695 $limitIds = array();
696 foreach ($limitCodes as $code) {
697 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
698 }
699 if (!empty($limitIds)) {
700 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
701 }
702 else {
703 $whereClause = FALSE;
704 }
705 }
706 self::populate(self::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
707
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',
714 ));
715 self::$stateProvince = CRM_Utils_Array::asort(self::$stateProvince);
716 }
717 }
718 if ($id) {
719 if (array_key_exists($id, self::$stateProvince)) {
720 return self::$stateProvince[$id];
721 }
722 else {
723 $result = NULL;
724 return $result;
725 }
726 }
727 return self::$stateProvince;
728 }
729
730 /**
731 * Get all the State/Province abbreviations from the database.
732 *
733 * Same as above, except gets the abbreviations instead of the names.
734 *
735 *
736 * @param bool|int $id - Optional id to return
737 *
738 * @param bool $limit
739 *
740 * @return array
741 * array reference of all State/Province abbreviations.
742 */
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
748 WHERE id = %1";
749 $params = array(
750 1 => array(
751 $id,
752 'Integer',
753 ),
754 );
755 self::$stateProvinceAbbreviation[$id] = CRM_Core_DAO::singleValueQuery($query, $params);
756 }
757 return self::$stateProvinceAbbreviation[$id];
758 }
759 else {
760 $whereClause = FALSE;
761
762 if ($limit) {
763 $countryIsoCodes = self::countryIsoCode();
764 $limitCodes = CRM_Core_BAO_Country::provinceLimit();
765 $limitIds = array();
766 foreach ($limitCodes as $code) {
767 $tmpArray = array_keys($countryIsoCodes, $code);
768
769 if (!empty($tmpArray)) {
770 $limitIds[] = array_shift($tmpArray);
771 }
772 }
773 if (!empty($limitIds)) {
774 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
775 }
776 }
777 self::populate(self::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
778 }
779
780 return self::$stateProvinceAbbreviation;
781 }
782
783 /**
784 * Get all the countries from database.
785 *
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.
789 *
790 * Note: any database errors will be trapped by the DAO.
791 *
792 *
793 * @param bool|int $id - Optional id to return
794 *
795 * @param bool $applyLimit
796 *
797 * @return array|null
798 * array reference of all countries.
799 */
800 public static function country($id = FALSE, $applyLimit = TRUE) {
801 if (($id && !CRM_Utils_Array::value($id, self::$country)) || !self::$country || !$id) {
802
803 $config = CRM_Core_Config::singleton();
804 $limitCodes = array();
805
806 if ($applyLimit) {
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)) {
812 $limitCodes = array(
813 $config->countryLimit => 1,
814 );
815 }
816
817 $limitCodes = array_intersect(self::countryIsoCode(), $limitCodes);
818 }
819
820 if (count($limitCodes)) {
821 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
822 }
823 else {
824 $whereClause = NULL;
825 }
826
827 self::populate(self::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
828
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;
836 }
837 }
838
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',
845 ));
846 self::$country = CRM_Utils_Array::asort(self::$country);
847 }
848 }
849 if ($id) {
850 if (array_key_exists($id, self::$country)) {
851 return self::$country[$id];
852 }
853 else {
854 return NULL;
855 }
856 }
857 return self::$country;
858 }
859
860 /**
861 * Get all the country ISO Code abbreviations from the database.
862 *
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.
866 *
867 * Note: any database errors will be trapped by the DAO.
868 *
869 *
870 * @param bool $id
871 *
872 * @return array
873 * array reference of all country ISO codes.
874 */
875 public static function &countryIsoCode($id = FALSE) {
876 if (!self::$countryIsoCode) {
877 self::populate(self::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
878 }
879 if ($id) {
880 if (array_key_exists($id, self::$countryIsoCode)) {
881 return self::$countryIsoCode[$id];
882 }
883 else {
884 return CRM_Core_DAO::$_nullObject;
885 }
886 }
887 return self::$countryIsoCode;
888 }
889
890 /**
891 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
892 *
893 * Get all groups from database
894 *
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.
898 *
899 * Note: any database errors will be trapped by the DAO.
900 *
901 * @param string $groupType
902 * Type of group(Access/Mailing).
903 * @param bool $excludeHidden
904 * Exclude hidden groups.
905 *
906 *
907 * @return array
908 * array reference of all groups.
909 */
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);
913
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);
916 }
917 return Civi::$statics[__CLASS__]['groups']['allGroup'][$groupKey];
918 }
919
920 /**
921 * Get all permissioned groups from database.
922 *
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.
926 *
927 * Note: any database errors will be trapped by the DAO.
928 *
929 * @param string $groupType
930 * Type of group(Access/Mailing).
931 * @param bool $excludeHidden
932 * Exclude hidden groups.
933 *
934 *
935 * @return array
936 * array reference of all groups.
937 */
938 public static function group($groupType = NULL, $excludeHidden = TRUE) {
939 return CRM_Core_Permission::group($groupType, $excludeHidden);
940 }
941
942 /**
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
947 * @return array
948 */
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, '&nbsp;&nbsp;', TRUE);
952 }
953
954 /**
955 * Get all permissioned groups from database.
956 *
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.
960 *
961 * Note: any database errors will be trapped by the DAO.
962 *
963 *
964 * @param bool $onlyPublic
965 * @param null $groupType
966 * @param bool $excludeHidden
967 *
968 * @return array
969 * array reference of all groups.
970 */
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';
974 if ($onlyPublic) {
975 $condition .= " AND visibility != 'User and User Admin Only'";
976 }
977
978 if ($groupType) {
979 $condition .= ' AND ' . CRM_Contact_BAO_Group::groupTypeCondition($groupType);
980 }
981
982 if ($excludeHidden) {
983 $condition .= ' AND is_hidden != 1 ';
984 }
985
986 self::populate(self::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
987 }
988
989 return self::$staticGroup;
990 }
991
992 /**
993 * Get all Relationship Types from database.
994 *
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.
998 *
999 * Note: any database errors will be trapped by the DAO.
1000 *
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.
1007 *
1008 * @return array
1009 * array reference of all relationship types.
1010 */
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();
1015
1016 //now we have name/label columns CRM-3336
1017 $column_a_b = "{$valueColumnName}_a_b";
1018 $column_b_a = "{$valueColumnName}_b_a";
1019
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;
1025 }
1026 $relationshipTypeDAO->find();
1027 while ($relationshipTypeDAO->fetch()) {
1028
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",
1037 );
1038 }
1039 }
1040
1041 return self::$relationshipType[$cacheKey];
1042 }
1043
1044 /**
1045 * Get all the ISO 4217 currency codes
1046 *
1047 * so far, we use this for validation only, so there's no point of putting this into the database
1048 *
1049 *
1050 * @return array
1051 * array reference of all currency codes
1052 */
1053 public static function &currencyCode() {
1054 if (!self::$currencyCode) {
1055 self::$currencyCode = array(
1056 'AFN',
1057 'ALL',
1058 'DZD',
1059 'USD',
1060 'EUR',
1061 'AOA',
1062 'XCD',
1063 'XCD',
1064 'ARS',
1065 'AMD',
1066 'AWG',
1067 'AUD',
1068 'EUR',
1069 'AZM',
1070 'BSD',
1071 'BHD',
1072 'BDT',
1073 'BBD',
1074 'BYR',
1075 'EUR',
1076 'BZD',
1077 'XOF',
1078 'BMD',
1079 'INR',
1080 'BTN',
1081 'BOB',
1082 'BOV',
1083 'BAM',
1084 'BWP',
1085 'NOK',
1086 'BRL',
1087 'USD',
1088 'BND',
1089 'BGN',
1090 'XOF',
1091 'BIF',
1092 'KHR',
1093 'XAF',
1094 'CAD',
1095 'CVE',
1096 'KYD',
1097 'XAF',
1098 'XAF',
1099 'CLP',
1100 'CLF',
1101 'CNY',
1102 'AUD',
1103 'AUD',
1104 'COP',
1105 'COU',
1106 'KMF',
1107 'XAF',
1108 'CDF',
1109 'NZD',
1110 'CRC',
1111 'XOF',
1112 'HRK',
1113 'CUP',
1114 'CYP',
1115 'CZK',
1116 'DKK',
1117 'DJF',
1118 'XCD',
1119 'DOP',
1120 'USD',
1121 'EGP',
1122 'SVC',
1123 'USD',
1124 'XAF',
1125 'ERN',
1126 'EEK',
1127 'ETB',
1128 'FKP',
1129 'DKK',
1130 'FJD',
1131 'EUR',
1132 'EUR',
1133 'EUR',
1134 'XPF',
1135 'EUR',
1136 'XAF',
1137 'GMD',
1138 'GEL',
1139 'EUR',
1140 'GHC',
1141 'GIP',
1142 'EUR',
1143 'DKK',
1144 'XCD',
1145 'EUR',
1146 'USD',
1147 'GTQ',
1148 'GNF',
1149 'GWP',
1150 'XOF',
1151 'GYD',
1152 'HTG',
1153 'USD',
1154 'AUD',
1155 'EUR',
1156 'HNL',
1157 'HKD',
1158 'HUF',
1159 'ISK',
1160 'INR',
1161 'IDR',
1162 'XDR',
1163 'IRR',
1164 'IQD',
1165 'EUR',
1166 'ILS',
1167 'EUR',
1168 'JMD',
1169 'JPY',
1170 'JOD',
1171 'KZT',
1172 'KES',
1173 'AUD',
1174 'KPW',
1175 'KRW',
1176 'KWD',
1177 'KGS',
1178 'LAK',
1179 'LVL',
1180 'LBP',
1181 'ZAR',
1182 'LSL',
1183 'LRD',
1184 'LYD',
1185 'CHF',
1186 'LTL',
1187 'EUR',
1188 'MOP',
1189 'MKD',
1190 'MGA',
1191 'MWK',
1192 'MYR',
1193 'MVR',
1194 'XOF',
1195 'MTL',
1196 'USD',
1197 'EUR',
1198 'MRO',
1199 'MUR',
1200 'EUR',
1201 'MXN',
1202 'MXV',
1203 'USD',
1204 'MDL',
1205 'EUR',
1206 'MNT',
1207 'XCD',
1208 'MAD',
1209 'MZM',
1210 'MMK',
1211 'ZAR',
1212 'NAD',
1213 'AUD',
1214 'NPR',
1215 'EUR',
1216 'ANG',
1217 'XPF',
1218 'NZD',
1219 'NIO',
1220 'XOF',
1221 'NGN',
1222 'NZD',
1223 'AUD',
1224 'USD',
1225 'NOK',
1226 'OMR',
1227 'PKR',
1228 'USD',
1229 'PAB',
1230 'USD',
1231 'PGK',
1232 'PYG',
1233 'PEN',
1234 'PHP',
1235 'NZD',
1236 'PLN',
1237 'EUR',
1238 'USD',
1239 'QAR',
1240 'EUR',
1241 'ROL',
1242 'RON',
1243 'RUB',
1244 'RWF',
1245 'SHP',
1246 'XCD',
1247 'XCD',
1248 'EUR',
1249 'XCD',
1250 'WST',
1251 'EUR',
1252 'STD',
1253 'SAR',
1254 'XOF',
1255 'CSD',
1256 'EUR',
1257 'SCR',
1258 'SLL',
1259 'SGD',
1260 'SKK',
1261 'SIT',
1262 'SBD',
1263 'SOS',
1264 'ZAR',
1265 'EUR',
1266 'LKR',
1267 'SDD',
1268 'SRD',
1269 'NOK',
1270 'SZL',
1271 'SEK',
1272 'CHF',
1273 'CHW',
1274 'CHE',
1275 'SYP',
1276 'TWD',
1277 'TJS',
1278 'TZS',
1279 'THB',
1280 'USD',
1281 'XOF',
1282 'NZD',
1283 'TOP',
1284 'TTD',
1285 'TND',
1286 'TRY',
1287 'TRL',
1288 'TMM',
1289 'USD',
1290 'AUD',
1291 'UGX',
1292 'UAH',
1293 'AED',
1294 'GBP',
1295 'USD',
1296 'USS',
1297 'USN',
1298 'USD',
1299 'UYU',
1300 'UZS',
1301 'VUV',
1302 'VEB',
1303 'VND',
1304 'USD',
1305 'USD',
1306 'XPF',
1307 'MAD',
1308 'YER',
1309 'ZMK',
1310 'ZWD',
1311 'XAU',
1312 'XBA',
1313 'XBB',
1314 'XBC',
1315 'XBD',
1316 'XPD',
1317 'XPT',
1318 'XAG',
1319 'XFU',
1320 'XFO',
1321 'XTS',
1322 'XXX',
1323 );
1324 }
1325 return self::$currencyCode;
1326 }
1327
1328 /**
1329 * Get all the County from database.
1330 *
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.
1334 *
1335 * Note: any database errors will be trapped by the DAO.
1336 *
1337 *
1338 * @param bool|int $id - Optional id to return
1339 *
1340 * @return array
1341 * array reference of all Counties
1342 */
1343 public static function &county($id = FALSE) {
1344 if (!self::$county) {
1345
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');
1349 }
1350 if ($id) {
1351 if (array_key_exists($id, self::$county)) {
1352 return self::$county[$id];
1353 }
1354 else {
1355 return CRM_Core_DAO::$_nullObject;
1356 }
1357 }
1358 return self::$county;
1359 }
1360
1361 /**
1362 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1363 * Get all active payment processors
1364 *
1365 * The static array paymentProcessor is returned
1366 *
1367 *
1368 * @param bool $all
1369 * Get payment processors - default is to get only active ones.
1370 * @param bool $test
1371 * Get test payment processors.
1372 *
1373 * @param null $additionalCond
1374 *
1375 * @return array
1376 * array of all payment processors
1377 */
1378 public static function paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1379 $condition = "is_test = ";
1380 $condition .= ($test) ? '1' : '0';
1381
1382 if ($additionalCond) {
1383 $condition .= " AND ( $additionalCond ) ";
1384 }
1385
1386 // CRM-7178. Make sure we only include payment processors valid in this
1387 // domain
1388 $condition .= " AND domain_id = " . CRM_Core_Config::domainID();
1389
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');
1393 }
1394
1395 return self::$paymentProcessor[$cacheKey];
1396 }
1397
1398 /**
1399 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1400 *
1401 * The static array paymentProcessorType is returned
1402 *
1403 *
1404 * @param bool $all
1405 * Get payment processors - default is to get only active ones.
1406 *
1407 * @param int $id
1408 * @param string $return
1409 *
1410 * @return array
1411 * array of all payment processor types
1412 */
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');
1417 }
1418 if ($id && CRM_Utils_Array::value($id, self::$paymentProcessorType[$cacheKey])) {
1419 return self::$paymentProcessorType[$cacheKey][$id];
1420 }
1421 return self::$paymentProcessorType[$cacheKey];
1422 }
1423
1424 /**
1425 * Get all the World Regions from Database.
1426 *
1427 *
1428 * @param bool $id
1429 *
1430 * @return array
1431 * array reference of all World Regions
1432 */
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');
1436 }
1437
1438 if ($id) {
1439 if (array_key_exists($id, self::$worldRegions)) {
1440 return self::$worldRegions[$id];
1441 }
1442 else {
1443 return CRM_Core_DAO::$_nullObject;
1444 }
1445 }
1446
1447 return self::$worldRegions;
1448 }
1449
1450 /**
1451 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1452 *
1453 * Get all Activity Statuses.
1454 *
1455 * The static array activityStatus is returned
1456 *
1457 *
1458 * @param string $column
1459 *
1460 * @return array
1461 * array reference of all activity statuses
1462 */
1463 public static function &activityStatus($column = 'label') {
1464 if (NULL === self::$activityStatus) {
1465 self::$activityStatus = array();
1466 }
1467 if (!array_key_exists($column, self::$activityStatus)) {
1468 self::$activityStatus[$column] = array();
1469
1470 self::$activityStatus[$column] = CRM_Core_OptionGroup::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1471 }
1472
1473 return self::$activityStatus[$column];
1474 }
1475
1476 /**
1477 * @deprecated Please use the buildOptions() method in the appropriate BAO object.
1478 *
1479 * Get all Visibility levels.
1480 *
1481 * The static array visibility is returned
1482 *
1483 *
1484 * @param string $column
1485 *
1486 * @return array
1487 * array reference of all Visibility levels.
1488 */
1489 public static function &visibility($column = 'label') {
1490 if (!isset(self::$visibility)) {
1491 self::$visibility = array();
1492 }
1493
1494 if (!isset(self::$visibility[$column])) {
1495 self::$visibility[$column] = CRM_Core_OptionGroup::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1496 }
1497
1498 return self::$visibility[$column];
1499 }
1500
1501 /**
1502 * @param int $countryID
1503 * @param string $field
1504 *
1505 * @return array
1506 */
1507 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1508 static $_cache = NULL;
1509
1510 $cacheKey = "{$countryID}_{$field}";
1511 if (!$_cache) {
1512 $_cache = array();
1513 }
1514
1515 if (!empty($_cache[$cacheKey])) {
1516 return $_cache[$cacheKey];
1517 }
1518
1519 $query = "
1520 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1521 FROM civicrm_state_province
1522 WHERE country_id = %1
1523 ORDER BY name";
1524 $params = array(
1525 1 => array(
1526 $countryID,
1527 'Integer',
1528 ),
1529 );
1530
1531 $dao = CRM_Core_DAO::executeQuery($query, $params);
1532
1533 $result = array();
1534 while ($dao->fetch()) {
1535 $result[$dao->id] = $dao->name;
1536 }
1537
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',
1545 ));
1546 $result = CRM_Utils_Array::asort($result);
1547 }
1548
1549 $_cache[$cacheKey] = $result;
1550
1551 CRM_Utils_Hook::buildStateProvinceForCountry($countryID, $result);
1552
1553 return $result;
1554 }
1555
1556 /**
1557 * @param int $stateID
1558 *
1559 * @return array
1560 */
1561 public static function &countyForState($stateID) {
1562 if (is_array($stateID)) {
1563 $states = implode(", ", $stateID);
1564 $query = "
1565 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1566 FROM civicrm_county
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";
1570
1571 $dao = CRM_Core_DAO::executeQuery($query);
1572
1573 $result = array();
1574 while ($dao->fetch()) {
1575 $result[$dao->id] = $dao->abbreviation . ': ' . $dao->name;
1576 }
1577 }
1578 else {
1579
1580 static $_cache = NULL;
1581
1582 $cacheKey = "{$stateID}_name";
1583 if (!$_cache) {
1584 $_cache = array();
1585 }
1586
1587 if (!empty($_cache[$cacheKey])) {
1588 return $_cache[$cacheKey];
1589 }
1590
1591 $query = "
1592 SELECT civicrm_county.name name, civicrm_county.id id
1593 FROM civicrm_county
1594 WHERE state_province_id = %1
1595 ORDER BY name";
1596 $params = array(
1597 1 => array(
1598 $stateID,
1599 'Integer',
1600 ),
1601 );
1602
1603 $dao = CRM_Core_DAO::executeQuery($query, $params);
1604
1605 $result = array();
1606 while ($dao->fetch()) {
1607 $result[$dao->id] = $dao->name;
1608 }
1609 }
1610
1611 return $result;
1612 }
1613
1614 /**
1615 * Given a state ID return the country ID, this allows
1616 * us to populate forms and values for downstream code
1617 *
1618 * @param int $stateID
1619 *
1620 * @return int|null
1621 * the country id that the state belongs to
1622 */
1623 public static function countryIDForStateID($stateID) {
1624 if (empty($stateID)) {
1625 return NULL;
1626 }
1627
1628 $query = "
1629 SELECT country_id
1630 FROM civicrm_state_province
1631 WHERE id = %1
1632 ";
1633 $params = array(1 => array($stateID, 'Integer'));
1634
1635 return CRM_Core_DAO::singleValueQuery($query, $params);
1636 }
1637
1638 /**
1639 * Get all types of Greetings.
1640 *
1641 * The static array of greeting is returned
1642 *
1643 *
1644 * @param $filter
1645 * Get All Email Greetings - default is to get only active ones.
1646 *
1647 * @param string $columnName
1648 *
1649 * @return array
1650 * array reference of all greetings.
1651 */
1652 public static function greeting($filter, $columnName = 'label') {
1653 $index = $filter['greeting_type'] . '_' . $columnName;
1654
1655 // also add contactType to the array
1656 $contactType = CRM_Utils_Array::value('contact_type', $filter);
1657 if ($contactType) {
1658 $index .= '_' . $contactType;
1659 }
1660
1661 if (NULL === self::$greeting) {
1662 self::$greeting = array();
1663 }
1664
1665 if (!CRM_Utils_Array::value($index, self::$greeting)) {
1666 $filterCondition = NULL;
1667 if ($contactType) {
1668 $filterVal = 'v.filter =';
1669 switch ($contactType) {
1670 case 'Individual':
1671 $filterVal .= "1";
1672 break;
1673
1674 case 'Household':
1675 $filterVal .= "2";
1676 break;
1677
1678 case 'Organization':
1679 $filterVal .= "3";
1680 break;
1681 }
1682 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1683 }
1684
1685 self::$greeting[$index] = CRM_Core_OptionGroup::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1686 }
1687
1688 return self::$greeting[$index];
1689 }
1690
1691 /**
1692 * Construct array of default greeting values for contact type.
1693 *
1694 *
1695 * @return array
1696 * array reference of default greetings.
1697 */
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',
1704 ));
1705
1706 foreach ($contactTypes as $filter => $contactType) {
1707 $filterCondition = " AND (v.filter = 0 OR v.filter = $filter) AND v.is_default = 1 ";
1708
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;
1712 }
1713 }
1714
1715 self::$greetingDefaults = $defaultGreetings;
1716 }
1717
1718 return self::$greetingDefaults;
1719 }
1720
1721 /**
1722 * Get all extensions.
1723 *
1724 * The static array extensions
1725 *
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.
1728 *
1729 *
1730 * @return array
1731 * array($fullyQualifiedName => $label) list of extensions
1732 */
1733 public static function &getExtensions() {
1734 if (!self::$extensions) {
1735 self::$extensions = array();
1736 $sql = '
1737 SELECT full_name, label
1738 FROM civicrm_extension
1739 WHERE is_active = 1
1740 ';
1741 $dao = CRM_Core_DAO::executeQuery($sql);
1742 while ($dao->fetch()) {
1743 self::$extensions[$dao->full_name] = $dao->label;
1744 }
1745 }
1746
1747 return self::$extensions;
1748 }
1749
1750 /**
1751 * Get all options values.
1752 *
1753 * The static array option values is returned
1754 *
1755 *
1756 * @param bool $optionGroupName
1757 * Get All Option Group values- default is to get only active ones.
1758 *
1759 * @param int $id
1760 * @param null $condition
1761 *
1762 * @return array
1763 * array reference of all Option Group Name
1764 */
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);
1769 }
1770 if ($id) {
1771 return CRM_Utils_Array::value($id, self::$accountOptionValues[$cacheKey]);
1772 }
1773
1774 return self::$accountOptionValues[$cacheKey];
1775 }
1776
1777 /**
1778 * Fetch the list of active extensions of type 'module'
1779 *
1780 * @param bool $fresh
1781 * Whether to forcibly reload extensions list from canonical store.
1782 *
1783 * @return array
1784 * array(array('prefix' => $, 'file' => $))
1785 */
1786 public static function getModuleExtensions($fresh = FALSE) {
1787 return CRM_Extension_System::singleton()->getMapper()->getActiveModuleFiles($fresh);
1788 }
1789
1790
1791 /**
1792 * Get all tax rates.
1793 *
1794 * The static array tax rates is returned
1795 *
1796 * @return array
1797 * array list of tax rates with the financial type
1798 */
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(
1803 'sequential' => 1,
1804 'option_group_id' => 'account_relationship',
1805 'name' => 'Sales Tax Account is',
1806 ));
1807 $value = array();
1808 if ($option['count'] !== 0) {
1809 if ($option['count'] > 1) {
1810 foreach ($option['values'] as $opt) {
1811 $value[] = $opt['value'];
1812 }
1813 }
1814 else {
1815 $value[] = $option['values'][0]['value'];
1816 }
1817 $where = 'AND efa.account_relationship IN (' . implode(', ', $value) . ' )';
1818 }
1819 else {
1820 $where = '';
1821 }
1822 $sql = "
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'
1827 {$where}
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;
1832 }
1833 }
1834
1835 return Civi::$statics[__CLASS__]['taxRates'];
1836 }
1837
1838 }