More robust ways to get pseudoconstant labels and names CRM-12464
[civicrm-core.git] / CRM / Core / PseudoConstant.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
47 * $Id$
48 *
49 */
50 class CRM_Core_PseudoConstant {
51
52 /**
53 * static cache for pseudoconstant arrays
54 * @var array
55 * @static
56 */
57 private static $cache;
58
59 /**
60 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
61 *
62 * activity type
63 * @var array
64 * @static
65 */
66 private static $activityType;
67
68 /**
69 * states, provinces
70 * @var array
71 * @static
72 */
73 private static $stateProvince;
74
75 /**
76 * counties
77 * @var array
78 * @static
79 */
80 private static $county;
81
82 /**
83 * states/provinces abbreviations
84 * @var array
85 * @static
86 */
87 private static $stateProvinceAbbreviation;
88
89 /**
90 * country
91 * @var array
92 * @static
93 */
94 private static $country;
95
96 /**
97 * countryIsoCode
98 * @var array
99 * @static
100 */
101 private static $countryIsoCode;
102
103 /**
104 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
105 *
106 * group
107 * @var array
108 * @static
109 */
110 private static $group;
111
112 /**
113 * groupIterator
114 * @var mixed
115 * @static
116 */
117 private static $groupIterator;
118
119 /**
120 * relationshipType
121 * @var array
122 * @static
123 */
124 private static $relationshipType;
125
126 /**
127 * civicrm groups that are not smart groups
128 * @var array
129 * @static
130 */
131 private static $staticGroup;
132
133 /**
134 * currency codes
135 * @var array
136 * @static
137 */
138 private static $currencyCode;
139
140 /**
141 * payment processor
142 * @var array
143 * @static
144 */
145 private static $paymentProcessor;
146
147 /**
148 * payment processor types
149 * @var array
150 * @static
151 */
152 private static $paymentProcessorType;
153
154 /**
155 * World Region
156 * @var array
157 * @static
158 */
159 private static $worldRegions;
160
161 /**
162 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
163 *
164 * activity status
165 * @var array
166 * @static
167 */
168 private static $activityStatus;
169
170 /**
171 * Visibility
172 * @var array
173 * @static
174 */
175 private static $visibility;
176
177 /**
178 * Greetings
179 * @var array
180 * @static
181 */
182 private static $greeting;
183
184 /**
185 * Default Greetings
186 * @var array
187 * @static
188 */
189 private static $greetingDefaults;
190
191 /**
192 * Extensions of type module
193 * @var array
194 * @static
195 */
196 private static $extensions;
197
198 /**
199 * Financial Account Type
200 * @var array
201 * @static
202 */
203 private static $accountOptionValues;
204
205 /**
206 * Low-level option getter, rarely accessed directly.
207 * NOTE: Rather than calling this function directly use CRM_*_BAO_*::buildOptions()
208 *
209 * @param String $daoName
210 * @param String $fieldName
211 * @param Array $params
212 * - name string name of the option group
213 * - flip boolean results are return in id => label format if false
214 * if true, the results are reversed
215 * - grouping boolean if true, return the value in 'grouping' column (currently unsupported for tables other than option_value)
216 * - localize boolean if true, localize the results before returning
217 * - condition string|array add condition(s) to the sql query - will be concatenated using 'AND'
218 * - keyColumn string the column to use for 'id'
219 * - labelColumn string the column to use for 'label'
220 * - orderColumn string the column to use for sorting, defaults to 'weight' column if one exists, else defaults to labelColumn
221 * - onlyActive boolean return only the action option values
222 * - fresh boolean ignore cache entries and go back to DB
223 * @param String $context: Context string
224 *
225 * @return Array on success, FALSE on error.
226 *
227 * @static
228 */
229 public static function get($daoName, $fieldName, $params = array(), $context = NULL) {
230 CRM_Core_DAO::buildOptionsContext($context);
231 $flip = !empty($params['flip']);
232 // Merge params with defaults
233 $params += array(
234 'grouping' => FALSE,
235 'localize' => FALSE,
236 'onlyActive' => ($context == 'validate' || $context == 'create') ? FALSE : TRUE,
237 'fresh' => FALSE,
238 );
239
240 // Custom fields are not in the schema
241 if (strpos($fieldName, 'custom_') === 0 && is_numeric($fieldName[7])) {
242 $customField = new CRM_Core_DAO_CustomField();
243 $customField->id = (int) substr($fieldName, 7);
244 $customField->find(TRUE);
245 $options = FALSE;
246
247 if (!empty($customField->option_group_id)) {
248 $options = CRM_Core_OptionGroup::valuesByID($customField->option_group_id,
249 $flip,
250 $params['grouping'],
251 $params['localize'],
252 // Note: for custom fields the 'name' column is NULL
253 CRM_Utils_Array::value('labelColumn', $params, 'label'),
254 $params['onlyActive'],
255 $params['fresh']
256 );
257 }
258 else {
259 if ($customField->data_type === 'StateProvince') {
260 $options = self::stateProvince();
261 }
262 elseif ($customField->data_type === 'Country') {
263 $options = $context == 'validate' ? self::countryIsoCode() : self::country();
264 }
265 elseif ($customField->data_type === 'Boolean') {
266 $options = $context == 'validate' ? array(0, 1) : array(1 => ts('Yes'), 0 => ts('No'));
267 }
268 $options = $options && $flip ? array_flip($options) : $options;
269 }
270 if ($options !== FALSE) {
271 CRM_Utils_Hook::customFieldOptions($customField->id, $options, FALSE);
272 }
273 $customField->free();
274 return $options;
275 }
276
277 // Core field: load schema
278 $dao = new $daoName;
279 $fields = $dao->fields();
280 $fieldKeys = $dao->fieldKeys();
281 $dao->free();
282
283 // Support "unique names" as well as sql names
284 $fieldKey = $fieldName;
285 if (empty($fields[$fieldKey])) {
286 $fieldKey = $fieldKeys[$fieldName];
287 }
288 // If neither worked then this field doesn't exist. Return false.
289 if (empty($fields[$fieldKey])) {
290 return FALSE;
291 }
292 $fieldSpec = $fields[$fieldKey];
293
294 // If the field is an enum, explode the enum definition and return the array.
295 if (isset($fieldSpec['enumValues'])) {
296 // use of a space after the comma is inconsistent in xml
297 $enumStr = str_replace(', ', ',', $fieldSpec['enumValues']);
298 $output = explode(',', $enumStr);
299 return array_combine($output, $output);
300 }
301
302 elseif (!empty($fieldSpec['pseudoconstant'])) {
303 $pseudoconstant = $fieldSpec['pseudoconstant'];
304 // Merge params with schema defaults
305 $params += array(
306 'condition' => CRM_Utils_Array::value('condition', $pseudoconstant, array()),
307 'keyColumn' => CRM_Utils_Array::value('keyColumn', $pseudoconstant),
308 'labelColumn' => CRM_Utils_Array::value('labelColumn', $pseudoconstant),
309 );
310
311 // Fetch option group from option_value table
312 if(!empty($pseudoconstant['optionGroupName'])) {
313 if ($context == 'validate') {
314 $params['labelColumn'] = 'name';
315 }
316 // Call our generic fn for retrieving from the option_value table
317 return CRM_Core_OptionGroup::values(
318 $pseudoconstant['optionGroupName'],
319 $flip,
320 $params['grouping'],
321 $params['localize'],
322 $params['condition'] ? ' AND ' . implode(' AND ', (array) $params['condition']) : NULL,
323 $params['labelColumn'] ? $params['labelColumn'] : 'label',
324 $params['onlyActive'],
325 $params['fresh'],
326 $params['keyColumn'] ? $params['keyColumn'] : 'value'
327 );
328 }
329
330 // Fetch options from other tables
331 if (!empty($pseudoconstant['table'])) {
332 // Normalize params so the serialized cache string will be consistent.
333 CRM_Utils_Array::remove($params, 'flip', 'fresh');
334 ksort($params);
335 $cacheKey = $daoName . $fieldName . serialize($params);
336
337 // Retrieve cached options
338 if (isset(self::$cache[$cacheKey]) && empty($params['fresh'])) {
339 $output = self::$cache[$cacheKey];
340 }
341 else {
342 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($pseudoconstant['table']);
343 if (!class_exists($daoName)) {
344 return FALSE;
345 }
346 // Get list of fields for the option table
347 $dao = new $daoName;
348 $availableFields = array_keys($dao->fieldKeys());
349 $dao->free();
350
351 $select = "SELECT %1 AS id, %2 AS label";
352 $from = "FROM %3";
353 $wheres = array();
354 $order = "ORDER BY %2";
355
356 // Use machine name instead of label in validate context
357 if ($context == 'validate') {
358 if (!empty($pseudoconstant['nameColumn'])) {
359 $params['labelColumn'] = $pseudoconstant['nameColumn'];
360 }
361 elseif (in_array('name', $availableFields)) {
362 $params['labelColumn'] = 'name';
363 }
364 }
365 // Condition param can be passed as an sql clause string or an array of clauses
366 if (!empty($params['condition'])) {
367 $wheres[] = implode(' AND ', (array) $params['condition']);
368 }
369 // onlyActive param will automatically filter on common flags
370 if (!empty($params['onlyActive'])) {
371 foreach (array('is_active' => 1, 'is_deleted' => 0, 'is_test' => 0) as $flag => $val) {
372 if (in_array($flag, $availableFields)) {
373 $wheres[] = "$flag = $val";
374 }
375 }
376 }
377 // Filter domain specific options
378 if (in_array('domain_id', $availableFields)) {
379 $wheres[] = 'domain_id = ' . CRM_Core_Config::domainID();
380 }
381 $queryParams = array(
382 1 => array($params['keyColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES),
383 2 => array($params['labelColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES),
384 3 => array($pseudoconstant['table'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES),
385 );
386 // Add orderColumn param
387 if (!empty($params['orderColumn'])) {
388 $queryParams[4] = array($params['orderColumn'], 'String', CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES);
389 $order = "ORDER BY %4";
390 }
391 // Support no sorting if $params[orderColumn] is FALSE
392 elseif (isset($params['orderColumn']) && $params['orderColumn'] === FALSE) {
393 $order = '';
394 }
395 // Default to 'weight' if that column exists
396 elseif (in_array('weight', $availableFields)) {
397 $order = "ORDER BY weight";
398 }
399
400 $output = array();
401 $query = "$select $from";
402 if ($wheres) {
403 $query .= " WHERE " . implode($wheres, ' AND ');
404 }
405 $query .= ' ' . $order;
406 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
407 while ($dao->fetch()) {
408 $output[$dao->id] = $dao->label;
409 }
410 $dao->free();
411 // Localize results
412 if (!empty($params['localize']) || $pseudoconstant['table'] == 'civicrm_country' || $pseudoconstant['table'] == 'civicrm_state_province') {
413 $I18nParams = array();
414 if ($pseudoconstant['table'] == 'civicrm_country') {
415 $I18nParams['context'] = 'country';
416 }
417 if ($pseudoconstant['table'] == 'civicrm_state_province') {
418 $I18nParams['context'] = 'province';
419 }
420 $i18n = CRM_Core_I18n::singleton();
421 $i18n->localizeArray($output, $I18nParams);
422 // Maintain sort by label
423 if ($order == "ORDER BY %2") {
424 CRM_Utils_Array::asort($output);
425 }
426 }
427 self::$cache[$cacheKey] = $output;
428 }
429 return $flip ? array_flip($output) : $output;
430 }
431 }
432
433 // Return "Yes" and "No" for boolean fields
434 elseif (CRM_Utils_Array::value('type', $fieldSpec) === CRM_Utils_Type::T_BOOLEAN) {
435 $output = $context == 'validate' ? array(0, 1) : array(1 => ts('Yes'), 0 => ts('No'));
436 return $flip ? array_flip($output) : $output;
437 }
438 // If we're still here, it's an error. Return FALSE.
439 return FALSE;
440 }
441
442 /**
443 * Fetch the translated label for a field given its key
444 *
445 * @param String $baoName
446 * @param String $fieldName
447 * @param String|Int $key
448 *
449 * TODO: Accept multivalued input?
450 *
451 * @return bool|null|string
452 * FALSE if the given field has no associated option list
453 * NULL if the given key has no corresponding option
454 * String if label is found
455 */
456 static function getLabel($baoName, $fieldName, $key) {
457 $values = $baoName::buildOptions($fieldName, 'get');
458 if ($values === FALSE) {
459 return FALSE;
460 }
461 return CRM_Utils_Array::value($key, $values);
462 }
463
464 /**
465 * Fetch the machine name for a field given its key
466 *
467 * @param String $baoName
468 * @param String $fieldName
469 * @param String|Int $key
470 *
471 * @return bool|null|string
472 * FALSE if the given field has no associated option list
473 * NULL if the given key has no corresponding option
474 * String if label is found
475 */
476 static function getName($baoName, $fieldName, $key) {
477 $values = $baoName::buildOptions($fieldName, 'validate');
478 if ($values === FALSE) {
479 return FALSE;
480 }
481 return CRM_Utils_Array::value($key, $values);
482 }
483
484 /**
485 * Fetch the key for a field option given its name
486 *
487 * @param String $baoName
488 * @param String $fieldName
489 * @param String|Int $value
490 *
491 * @return bool|null|string|number
492 * FALSE if the given field has no associated option list
493 * NULL if the given key has no corresponding option
494 * String|Number if key is found
495 */
496 static function getKey($baoName, $fieldName, $value) {
497 $values = $baoName::buildOptions($fieldName, 'validate');
498 if ($values === FALSE) {
499 return FALSE;
500 }
501 return CRM_Utils_Array::key($value, $values);
502 }
503
504 /**
505 * DEPRECATED generic populate method
506 * All pseudoconstant functions that use this method are also deprecated.
507 *
508 * The static array $var is populated from the db
509 * using the <b>$name DAO</b>.
510 *
511 * Note: any database errors will be trapped by the DAO.
512 *
513 * @param array $var the associative array we will fill
514 * @param string $name the name of the DAO
515 * @param boolean $all get all objects. default is to get only active ones.
516 * @param string $retrieve the field that we are interested in (normally name, differs in some objects)
517 * @param string $filter the field that we want to filter the result set with
518 * @param string $condition the condition that gets passed to the final query as the WHERE clause
519 *
520 * @return void
521 * @access public
522 * @static
523 */
524 public static function populate(
525 &$var,
526 $name,
527 $all = FALSE,
528 $retrieve = 'name',
529 $filter = 'is_active',
530 $condition = NULL,
531 $orderby = NULL,
532 $key = 'id',
533 $force = NULL
534 ) {
535 $cacheKey = "CRM_PC_{$name}_{$all}_{$key}_{$retrieve}_{$filter}_{$condition}_{$orderby}";
536 $cache = CRM_Utils_Cache::singleton();
537 $var = $cache->get($cacheKey);
538 if ($var && empty($force)) {
539 return $var;
540 }
541
542 $object = new $name ( );
543
544 $object->selectAdd();
545 $object->selectAdd("$key, $retrieve");
546 if ($condition) {
547 $object->whereAdd($condition);
548 }
549
550 if (!$orderby) {
551 $object->orderBy($retrieve);
552 }
553 else {
554 $object->orderBy($orderby);
555 }
556
557 if (!$all) {
558 $object->$filter = 1;
559 }
560
561 $object->find();
562 $var = array();
563 while ($object->fetch()) {
564 $var[$object->$key] = $object->$retrieve;
565 }
566
567 $cache->set($cacheKey, $var);
568 }
569
570 /**
571 * Flush given pseudoconstant so it can be reread from db
572 * nex time it's requested.
573 *
574 * @access public
575 * @static
576 *
577 * @param boolean $name pseudoconstant to be flushed
578 *
579 */
580 public static function flush($name = 'cache') {
581 if (isset(self::$$name)) {
582 self::$$name = NULL;
583 }
584 if ($name == 'cache') {
585 CRM_Core_OptionGroup::flushAll();
586 }
587 }
588
589 /**
590 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
591 *
592 * Get all Activty types.
593 *
594 * The static array activityType is returned
595 *
596 * @param boolean $all - get All Activity types - default is to get only active ones.
597 *
598 * @access public
599 * @static
600 *
601 * @return array - array reference of all activity types.
602 */
603 public static function &activityType() {
604 $args = func_get_args();
605 $all = CRM_Utils_Array::value(0, $args, TRUE);
606 $includeCaseActivities = CRM_Utils_Array::value(1, $args, FALSE);
607 $reset = CRM_Utils_Array::value(2, $args, FALSE);
608 $returnColumn = CRM_Utils_Array::value(3, $args, 'label');
609 $includeCampaignActivities = CRM_Utils_Array::value(4, $args, FALSE);
610 $onlyComponentActivities = CRM_Utils_Array::value(5, $args, FALSE);
611 $index = (int) $all . '_' . $returnColumn . '_' . (int) $includeCaseActivities;
612 $index .= '_' . (int) $includeCampaignActivities;
613 $index .= '_' . (int) $onlyComponentActivities;
614
615 if (NULL === self::$activityType) {
616 self::$activityType = array();
617 }
618
619 if (!isset(self::$activityType[$index]) || $reset) {
620 $condition = NULL;
621 if (!$all) {
622 $condition = 'AND filter = 0';
623 }
624 $componentClause = " v.component_id IS NULL";
625 if ($onlyComponentActivities) {
626 $componentClause = " v.component_id IS NOT NULL";
627 }
628
629 $componentIds = array();
630 $compInfo = CRM_Core_Component::getEnabledComponents();
631
632 // build filter for listing activity types only if their
633 // respective components are enabled
634 foreach ($compInfo as $compName => $compObj) {
635 if ($compName == 'CiviCase') {
636 if ($includeCaseActivities) {
637 $componentIds[] = $compObj->componentID;
638 }
639 }
640 elseif ($compName == 'CiviCampaign') {
641 if ($includeCampaignActivities) {
642 $componentIds[] = $compObj->componentID;
643 }
644 }
645 else {
646 $componentIds[] = $compObj->componentID;
647 }
648 }
649
650 if (count($componentIds)) {
651 $componentIds = implode(',', $componentIds);
652 $componentClause = " ($componentClause OR v.component_id IN ($componentIds))";
653 if ($onlyComponentActivities) {
654 $componentClause = " ( v.component_id IN ($componentIds ) )";
655 }
656 }
657 $condition = $condition . ' AND ' . $componentClause;
658
659 self::$activityType[$index] = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
660 }
661 return self::$activityType[$index];
662 }
663
664 /**
665 * Get all the State/Province from database.
666 *
667 * The static array stateProvince is returned, and if it's
668 * called the first time, the <b>State Province DAO</b> is used
669 * to get all the States.
670 *
671 * Note: any database errors will be trapped by the DAO.
672 *
673 * @access public
674 * @static
675 *
676 * @param int $id - Optional id to return
677 *
678 * @return array - array reference of all State/Provinces.
679 *
680 */
681 public static function &stateProvince($id = FALSE, $limit = TRUE) {
682 if (($id && !CRM_Utils_Array::value($id, self::$stateProvince)) || !self::$stateProvince || !$id) {
683 $whereClause = FALSE;
684 $config = CRM_Core_Config::singleton();
685 if ($limit) {
686 $countryIsoCodes = self::countryIsoCode();
687 $limitCodes = $config->provinceLimit();
688 $limitIds = array();
689 foreach ($limitCodes as $code) {
690 $limitIds = array_merge($limitIds, array_keys($countryIsoCodes, $code));
691 }
692 if (!empty($limitIds)) {
693 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
694 }
695 else {
696 $whereClause = FALSE;
697 }
698 }
699 self::populate(self::$stateProvince, 'CRM_Core_DAO_StateProvince', TRUE, 'name', 'is_active', $whereClause);
700
701 // localise the province names if in an non-en_US locale
702 global $tsLocale;
703 if ($tsLocale != '' and $tsLocale != 'en_US') {
704 $i18n = CRM_Core_I18n::singleton();
705 $i18n->localizeArray(self::$stateProvince, array(
706 'context' => 'province',
707 ));
708 self::$stateProvince = CRM_Utils_Array::asort(self::$stateProvince);
709 }
710 }
711 if ($id) {
712 if (array_key_exists($id, self::$stateProvince)) {
713 return self::$stateProvince[$id];
714 }
715 else {
716 $result = NULL;
717 return $result;
718 }
719 }
720 return self::$stateProvince;
721 }
722
723 /**
724 * Get all the State/Province abbreviations from the database.
725 *
726 * Same as above, except gets the abbreviations instead of the names.
727 *
728 * @access public
729 * @static
730 *
731 * @param int $id - Optional id to return
732 *
733 * @return array - array reference of all State/Province abbreviations.
734 */
735 public static function &stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
736 if ($id > 1) {
737 $query = "
738 SELECT abbreviation
739 FROM civicrm_state_province
740 WHERE id = %1";
741 $params = array(
742 1 => array(
743 $id,
744 'Integer',
745 ),
746 );
747 return CRM_Core_DAO::singleValueQuery($query, $params);
748 }
749
750 if (!self::$stateProvinceAbbreviation || !$id) {
751
752 $whereClause = FALSE;
753
754 if ($limit) {
755 $config = CRM_Core_Config::singleton();
756 $countryIsoCodes = self::countryIsoCode();
757 $limitCodes = $config->provinceLimit();
758 $limitIds = array();
759 foreach ($limitCodes as $code) {
760 $tmpArray = array_keys($countryIsoCodes, $code);
761
762 if (!empty($tmpArray)) {
763 $limitIds[] = array_shift($tmpArray);
764 }
765 }
766 if (!empty($limitIds)) {
767 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
768 }
769 }
770 self::populate(self::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
771 }
772
773 if ($id) {
774 if (array_key_exists($id, self::$stateProvinceAbbreviation)) {
775 return self::$stateProvinceAbbreviation[$id];
776 }
777 else {
778 $result = NULL;
779 return $result;
780 }
781 }
782 return self::$stateProvinceAbbreviation;
783 }
784
785 /**
786 * Get all the countries from database.
787 *
788 * The static array country is returned, and if it's
789 * called the first time, the <b>Country DAO</b> is used
790 * to get all the countries.
791 *
792 * Note: any database errors will be trapped by the DAO.
793 *
794 * @access public
795 * @static
796 *
797 * @param int $id - Optional id to return
798 *
799 * @return array - array reference of all countries.
800 *
801 */
802 public static function country($id = FALSE, $applyLimit = TRUE) {
803 if (($id && !CRM_Utils_Array::value($id, self::$country)) || !self::$country || !$id) {
804
805 $config = CRM_Core_Config::singleton();
806 $limitCodes = array();
807
808 if ($applyLimit) {
809 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
810 // (ensuring it's a subset of the legal values)
811 // K/P: We need to fix this, i dont think it works with new setting files
812 $limitCodes = $config->countryLimit();
813 if (!is_array($limitCodes)) {
814 $limitCodes = array(
815 $config->countryLimit => 1,
816 );
817 }
818
819 $limitCodes = array_intersect(self::countryIsoCode(), $limitCodes);
820 }
821
822 if (count($limitCodes)) {
823 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
824 }
825 else {
826 $whereClause = NULL;
827 }
828
829 self::populate(self::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
830
831 // if default country is set, percolate it to the top
832 if ($config->defaultContactCountry()) {
833 $countryIsoCodes = self::countryIsoCode();
834 $defaultID = array_search($config->defaultContactCountry(), $countryIsoCodes);
835 if ($defaultID !== FALSE) {
836 $default[$defaultID] = CRM_Utils_Array::value($defaultID, self::$country);
837 self::$country = $default + self::$country;
838 }
839 }
840
841 // localise the country names if in an non-en_US locale
842 global $tsLocale;
843 if ($tsLocale != '' and $tsLocale != 'en_US') {
844 $i18n = CRM_Core_I18n::singleton();
845 $i18n->localizeArray(self::$country, array(
846 'context' => 'country',
847 ));
848 self::$country = CRM_Utils_Array::asort(self::$country);
849 }
850 }
851 if ($id) {
852 if (array_key_exists($id, self::$country)) {
853 return self::$country[$id];
854 }
855 else {
856 return CRM_Core_DAO::$_nullObject;
857 }
858 }
859 return self::$country;
860 }
861
862 /**
863 * Get all the country ISO Code abbreviations from the database.
864 *
865 * The static array countryIsoCode is returned, and if it's
866 * called the first time, the <b>Country DAO</b> is used
867 * to get all the countries' ISO codes.
868 *
869 * Note: any database errors will be trapped by the DAO.
870 *
871 * @access public
872 * @static
873 *
874 * @return array - array reference of all country ISO codes.
875 *
876 */
877 public static function &countryIsoCode($id = FALSE) {
878 if (!self::$countryIsoCode) {
879 self::populate(self::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
880 }
881 if ($id) {
882 if (array_key_exists($id, self::$countryIsoCode)) {
883 return self::$countryIsoCode[$id];
884 }
885 else {
886 return CRM_Core_DAO::$_nullObject;
887 }
888 }
889 return self::$countryIsoCode;
890 }
891
892 /**
893 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
894 *
895 * Get all groups from database
896 *
897 * The static array group is returned, and if it's
898 * called the first time, the <b>Group DAO</b> is used
899 * to get all the groups.
900 *
901 * Note: any database errors will be trapped by the DAO.
902 *
903 * @param string $groupType type of group(Access/Mailing)
904 * @param boolen $excludeHidden exclude hidden groups.
905 *
906 * @access public
907 * @static
908 *
909 * @return array - array reference of all groups.
910 *
911 */
912 public static function &allGroup($groupType = NULL, $excludeHidden = TRUE) {
913 $condition = CRM_Contact_BAO_Group::groupTypeCondition($groupType, $excludeHidden);
914
915 if (!self::$group) {
916 self::$group = array();
917 }
918
919 $groupKey = $groupType ? $groupType : 'null';
920
921 if (!isset(self::$group[$groupKey])) {
922 self::$group[$groupKey] = NULL;
923 self::populate(self::$group[$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
924 }
925 return self::$group[$groupKey];
926 }
927
928 /**
929 * Create or get groups iterator (iterates over nested groups in a
930 * logical fashion)
931 *
932 * The GroupNesting instance is returned; it's created if this is being
933 * called for the first time
934 *
935 *
936 * @access public
937 * @static
938 *
939 * @return mixed - instance of CRM_Contact_BAO_GroupNesting
940 *
941 */
942 public static function &groupIterator($styledLabels = FALSE) {
943 if (!self::$groupIterator) {
944 /*
945 When used as an object, GroupNesting implements Iterator
946 and iterates nested groups in a logical manner for us
947 */
948 self::$groupIterator = new CRM_Contact_BAO_GroupNesting($styledLabels);
949 }
950 return self::$groupIterator;
951 }
952
953 /**
954 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
955 *
956 * Get all permissioned groups from database
957 *
958 * The static array group is returned, and if it's
959 * called the first time, the <b>Group DAO</b> is used
960 * to get all the groups.
961 *
962 * Note: any database errors will be trapped by the DAO.
963 *
964 * @param string $groupType type of group(Access/Mailing)
965 * @param boolen $excludeHidden exclude hidden groups.
966
967 * @access public
968 * @static
969 *
970 * @return array - array reference of all groups.
971 *
972 */
973 public static function group($groupType = NULL, $excludeHidden = TRUE) {
974 return CRM_Core_Permission::group($groupType, $excludeHidden);
975 }
976
977 /**
978 * Get all permissioned groups from database
979 *
980 * The static array group is returned, and if it's
981 * called the first time, the <b>Group DAO</b> is used
982 * to get all the groups.
983 *
984 * Note: any database errors will be trapped by the DAO.
985 *
986 * @access public
987 * @static
988 *
989 * @return array - array reference of all groups.
990 *
991 */
992 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
993 if (!self::$staticGroup) {
994 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
995 if ($onlyPublic) {
996 $condition .= " AND visibility != 'User and User Admin Only'";
997 }
998
999 if ($groupType) {
1000 $condition .= ' AND ' . CRM_Contact_BAO_Group::groupTypeCondition($groupType);
1001 }
1002
1003 if ($excludeHidden) {
1004 $condition .= ' AND is_hidden != 1 ';
1005 }
1006
1007 self::populate(self::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
1008 }
1009
1010 return self::$staticGroup;
1011 }
1012
1013 /**
1014 * Get all Relationship Types from database.
1015 *
1016 * The static array group is returned, and if it's
1017 * called the first time, the <b>RelationshipType DAO</b> is used
1018 * to get all the relationship types.
1019 *
1020 * Note: any database errors will be trapped by the DAO.
1021 *
1022 * @param string $valueColumnName db column name/label.
1023 * @param boolean $reset reset relationship types if true
1024 *
1025 * @access public
1026 * @static
1027 *
1028 * @return array - array reference of all relationship types.
1029 */
1030 public static function &relationshipType($valueColumnName = 'label', $reset = FALSE) {
1031 if (!CRM_Utils_Array::value($valueColumnName, self::$relationshipType) || $reset) {
1032 self::$relationshipType[$valueColumnName] = array();
1033
1034 //now we have name/label columns CRM-3336
1035 $column_a_b = "{$valueColumnName}_a_b";
1036 $column_b_a = "{$valueColumnName}_b_a";
1037
1038 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1039 $relationshipTypeDAO->selectAdd();
1040 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1041 $relationshipTypeDAO->is_active = 1;
1042 $relationshipTypeDAO->find();
1043 while ($relationshipTypeDAO->fetch()) {
1044
1045 self::$relationshipType[$valueColumnName][$relationshipTypeDAO->id] = array(
1046 $column_a_b => $relationshipTypeDAO->$column_a_b,
1047 $column_b_a => $relationshipTypeDAO->$column_b_a,
1048 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1049 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1050 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1051 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1052 );
1053 }
1054 }
1055
1056 return self::$relationshipType[$valueColumnName];
1057 }
1058
1059 /**
1060 * get all the ISO 4217 currency codes
1061 *
1062 * so far, we use this for validation only, so there's no point of putting this into the database
1063 *
1064 * @access public
1065 *
1066 * @return array - array reference of all currency codes
1067 * @static
1068 */
1069 public static function &currencyCode() {
1070 if (!self::$currencyCode) {
1071 self::$currencyCode = array(
1072 'AFN',
1073 'ALL',
1074 'DZD',
1075 'USD',
1076 'EUR',
1077 'AOA',
1078 'XCD',
1079 'XCD',
1080 'ARS',
1081 'AMD',
1082 'AWG',
1083 'AUD',
1084 'EUR',
1085 'AZM',
1086 'BSD',
1087 'BHD',
1088 'BDT',
1089 'BBD',
1090 'BYR',
1091 'EUR',
1092 'BZD',
1093 'XOF',
1094 'BMD',
1095 'INR',
1096 'BTN',
1097 'BOB',
1098 'BOV',
1099 'BAM',
1100 'BWP',
1101 'NOK',
1102 'BRL',
1103 'USD',
1104 'BND',
1105 'BGN',
1106 'XOF',
1107 'BIF',
1108 'KHR',
1109 'XAF',
1110 'CAD',
1111 'CVE',
1112 'KYD',
1113 'XAF',
1114 'XAF',
1115 'CLP',
1116 'CLF',
1117 'CNY',
1118 'AUD',
1119 'AUD',
1120 'COP',
1121 'COU',
1122 'KMF',
1123 'XAF',
1124 'CDF',
1125 'NZD',
1126 'CRC',
1127 'XOF',
1128 'HRK',
1129 'CUP',
1130 'CYP',
1131 'CZK',
1132 'DKK',
1133 'DJF',
1134 'XCD',
1135 'DOP',
1136 'USD',
1137 'EGP',
1138 'SVC',
1139 'USD',
1140 'XAF',
1141 'ERN',
1142 'EEK',
1143 'ETB',
1144 'FKP',
1145 'DKK',
1146 'FJD',
1147 'EUR',
1148 'EUR',
1149 'EUR',
1150 'XPF',
1151 'EUR',
1152 'XAF',
1153 'GMD',
1154 'GEL',
1155 'EUR',
1156 'GHC',
1157 'GIP',
1158 'EUR',
1159 'DKK',
1160 'XCD',
1161 'EUR',
1162 'USD',
1163 'GTQ',
1164 'GNF',
1165 'GWP',
1166 'XOF',
1167 'GYD',
1168 'HTG',
1169 'USD',
1170 'AUD',
1171 'EUR',
1172 'HNL',
1173 'HKD',
1174 'HUF',
1175 'ISK',
1176 'INR',
1177 'IDR',
1178 'XDR',
1179 'IRR',
1180 'IQD',
1181 'EUR',
1182 'ILS',
1183 'EUR',
1184 'JMD',
1185 'JPY',
1186 'JOD',
1187 'KZT',
1188 'KES',
1189 'AUD',
1190 'KPW',
1191 'KRW',
1192 'KWD',
1193 'KGS',
1194 'LAK',
1195 'LVL',
1196 'LBP',
1197 'ZAR',
1198 'LSL',
1199 'LRD',
1200 'LYD',
1201 'CHF',
1202 'LTL',
1203 'EUR',
1204 'MOP',
1205 'MKD',
1206 'MGA',
1207 'MWK',
1208 'MYR',
1209 'MVR',
1210 'XOF',
1211 'MTL',
1212 'USD',
1213 'EUR',
1214 'MRO',
1215 'MUR',
1216 'EUR',
1217 'MXN',
1218 'MXV',
1219 'USD',
1220 'MDL',
1221 'EUR',
1222 'MNT',
1223 'XCD',
1224 'MAD',
1225 'MZM',
1226 'MMK',
1227 'ZAR',
1228 'NAD',
1229 'AUD',
1230 'NPR',
1231 'EUR',
1232 'ANG',
1233 'XPF',
1234 'NZD',
1235 'NIO',
1236 'XOF',
1237 'NGN',
1238 'NZD',
1239 'AUD',
1240 'USD',
1241 'NOK',
1242 'OMR',
1243 'PKR',
1244 'USD',
1245 'PAB',
1246 'USD',
1247 'PGK',
1248 'PYG',
1249 'PEN',
1250 'PHP',
1251 'NZD',
1252 'PLN',
1253 'EUR',
1254 'USD',
1255 'QAR',
1256 'EUR',
1257 'ROL',
1258 'RON',
1259 'RUB',
1260 'RWF',
1261 'SHP',
1262 'XCD',
1263 'XCD',
1264 'EUR',
1265 'XCD',
1266 'WST',
1267 'EUR',
1268 'STD',
1269 'SAR',
1270 'XOF',
1271 'CSD',
1272 'EUR',
1273 'SCR',
1274 'SLL',
1275 'SGD',
1276 'SKK',
1277 'SIT',
1278 'SBD',
1279 'SOS',
1280 'ZAR',
1281 'EUR',
1282 'LKR',
1283 'SDD',
1284 'SRD',
1285 'NOK',
1286 'SZL',
1287 'SEK',
1288 'CHF',
1289 'CHW',
1290 'CHE',
1291 'SYP',
1292 'TWD',
1293 'TJS',
1294 'TZS',
1295 'THB',
1296 'USD',
1297 'XOF',
1298 'NZD',
1299 'TOP',
1300 'TTD',
1301 'TND',
1302 'TRY',
1303 'TRL',
1304 'TMM',
1305 'USD',
1306 'AUD',
1307 'UGX',
1308 'UAH',
1309 'AED',
1310 'GBP',
1311 'USD',
1312 'USS',
1313 'USN',
1314 'USD',
1315 'UYU',
1316 'UZS',
1317 'VUV',
1318 'VEB',
1319 'VND',
1320 'USD',
1321 'USD',
1322 'XPF',
1323 'MAD',
1324 'YER',
1325 'ZMK',
1326 'ZWD',
1327 'XAU',
1328 'XBA',
1329 'XBB',
1330 'XBC',
1331 'XBD',
1332 'XPD',
1333 'XPT',
1334 'XAG',
1335 'XFU',
1336 'XFO',
1337 'XTS',
1338 'XXX',
1339 );
1340 }
1341 return self::$currencyCode;
1342 }
1343
1344 /**
1345 * Get all the County from database.
1346 *
1347 * The static array county is returned, and if it's
1348 * called the first time, the <b>County DAO</b> is used
1349 * to get all the Counties.
1350 *
1351 * Note: any database errors will be trapped by the DAO.
1352 *
1353 * @access public
1354 * @static
1355 *
1356 * @param int $id - Optional id to return
1357 *
1358 * @return array - array reference of all Counties
1359 *
1360 */
1361 public static function &county($id = FALSE) {
1362 if (!self::$county) {
1363
1364 $config = CRM_Core_Config::singleton();
1365 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1366 self::populate(self::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1367 }
1368 if ($id) {
1369 if (array_key_exists($id, self::$county)) {
1370 return self::$county[$id];
1371 }
1372 else {
1373 return CRM_Core_DAO::$_nullObject;
1374 }
1375 }
1376 return self::$county;
1377 }
1378
1379 /**
1380 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
1381 * Get all active payment processors
1382 *
1383 * The static array paymentProcessor is returned
1384 *
1385 * @access public
1386 * @static
1387 *
1388 * @param boolean $all - get payment processors - default is to get only active ones.
1389 * @param boolean $test - get test payment processors
1390 *
1391 * @return array - array of all payment processors
1392 *
1393 */
1394 public static function &paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1395 $condition = "is_test = ";
1396 $condition .= ($test) ? '1' : '0';
1397
1398 if ($additionalCond) {
1399 $condition .= " AND ( $additionalCond ) ";
1400 }
1401
1402 // CRM-7178. Make sure we only include payment processors valid in ths
1403 // domain
1404 $condition .= " AND domain_id = " . CRM_Core_Config::domainID();
1405
1406 $cacheKey = $condition . '_' . (int) $all;
1407 if (!isset(self::$paymentProcessor[$cacheKey])) {
1408 self::populate(self::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1409 }
1410
1411 return self::$paymentProcessor[$cacheKey];
1412 }
1413
1414 /**
1415 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
1416 *
1417 * The static array paymentProcessorType is returned
1418 *
1419 * @access public
1420 * @static
1421 *
1422 * @param boolean $all - get payment processors - default is to get only active ones.
1423 *
1424 * @return array - array of all payment processor types
1425 *
1426 */
1427 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1428 $cacheKey = $id . '_' .$return;
1429 if (empty(self::$paymentProcessorType[$cacheKey])) {
1430 self::populate(self::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1431 }
1432 if ($id && CRM_Utils_Array::value($id, self::$paymentProcessorType[$cacheKey])) {
1433 return self::$paymentProcessorType[$cacheKey][$id];
1434 }
1435 return self::$paymentProcessorType[$cacheKey];
1436 }
1437
1438 /**
1439 * Get all the World Regions from Database
1440 *
1441 * @access public
1442 *
1443 * @return array - array reference of all World Regions
1444 * @static
1445 */
1446 public static function &worldRegion($id = FALSE) {
1447 if (!self::$worldRegions) {
1448 self::populate(self::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1449 }
1450
1451 if ($id) {
1452 if (array_key_exists($id, self::$worldRegions)) {
1453 return self::$worldRegions[$id];
1454 }
1455 else {
1456 return CRM_Core_DAO::$_nullObject;
1457 }
1458 }
1459
1460 return self::$worldRegions;
1461 }
1462
1463 /**
1464 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
1465 *
1466 * Get all Activity Statuses.
1467 *
1468 * The static array activityStatus is returned
1469 *
1470 * @access public
1471 * @static
1472 *
1473 * @return array - array reference of all activity statuses
1474 */
1475 public static function &activityStatus($column = 'label') {
1476 if (NULL === self::$activityStatus) {
1477 self::$activityStatus = array();
1478 }
1479 if (!array_key_exists($column, self::$activityStatus)) {
1480 self::$activityStatus[$column] = array();
1481
1482 self::$activityStatus[$column] = CRM_Core_OptionGroup::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1483 }
1484
1485 return self::$activityStatus[$column];
1486 }
1487
1488 /**
1489 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
1490 *
1491 * Get all Visibility levels.
1492 *
1493 * The static array visibility is returned
1494 *
1495 * @access public
1496 * @static
1497 *
1498 * @return array - array reference of all Visibility levels.
1499 *
1500 */
1501 public static function &visibility($column = 'label') {
1502 if (!isset(self::$visibility)) {
1503 self::$visibility = array( );
1504 }
1505
1506 if (!isset(self::$visibility[$column])) {
1507 self::$visibility[$column] = CRM_Core_OptionGroup::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1508 }
1509
1510 return self::$visibility[$column];
1511 }
1512
1513 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1514 static $_cache = NULL;
1515
1516 $cacheKey = "{$countryID}_{$field}";
1517 if (!$_cache) {
1518 $_cache = array();
1519 }
1520
1521 if (!empty($_cache[$cacheKey])) {
1522 return $_cache[$cacheKey];
1523 }
1524
1525 $query = "
1526 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1527 FROM civicrm_state_province
1528 WHERE country_id = %1
1529 ORDER BY name";
1530 $params = array(
1531 1 => array(
1532 $countryID,
1533 'Integer',
1534 ),
1535 );
1536
1537 $dao = CRM_Core_DAO::executeQuery($query, $params);
1538
1539 $result = array();
1540 while ($dao->fetch()) {
1541 $result[$dao->id] = $dao->name;
1542 }
1543
1544 // localise the stateProvince names if in an non-en_US locale
1545 $config = CRM_Core_Config::singleton();
1546 global $tsLocale;
1547 if ($tsLocale != '' and $tsLocale != 'en_US') {
1548 $i18n = CRM_Core_I18n::singleton();
1549 $i18n->localizeArray($result, array(
1550 'context' => 'province',
1551 ));
1552 $result = CRM_Utils_Array::asort($result);
1553 }
1554
1555 $_cache[$cacheKey] = $result;
1556
1557 CRM_Utils_Hook::buildStateProvinceForCountry($countryID, $result);
1558
1559 return $result;
1560 }
1561
1562 public static function &countyForState($stateID) {
1563 if (is_array($stateID)) {
1564 $states = implode(", ", $stateID);
1565 $query = "
1566 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1567 FROM civicrm_county
1568 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1569 WHERE civicrm_county.state_province_id in ( $states )
1570 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1571
1572 $dao = CRM_Core_DAO::executeQuery($query);
1573
1574 $result = array();
1575 while ($dao->fetch()) {
1576 $result[$dao->id] = $dao->abbreviation . ': ' . $dao->name;
1577 }
1578 }
1579 else {
1580
1581 static $_cache = NULL;
1582
1583 $cacheKey = "{$stateID}_name";
1584 if (!$_cache) {
1585 $_cache = array();
1586 }
1587
1588 if (!empty($_cache[$cacheKey])) {
1589 return $_cache[$cacheKey];
1590 }
1591
1592 $query = "
1593 SELECT civicrm_county.name name, civicrm_county.id id
1594 FROM civicrm_county
1595 WHERE state_province_id = %1
1596 ORDER BY name";
1597 $params = array(
1598 1 => array(
1599 $stateID,
1600 'Integer',
1601 ),
1602 );
1603
1604 $dao = CRM_Core_DAO::executeQuery($query, $params);
1605
1606 $result = array();
1607 while ($dao->fetch()) {
1608 $result[$dao->id] = $dao->name;
1609 }
1610 }
1611
1612 return $result;
1613 }
1614
1615 /**
1616 * Given a state ID return the country ID, this allows
1617 * us to populate forms and values for downstream code
1618 *
1619 * @param $stateID int
1620 *
1621 * @return int the country id that the state belongs to
1622 * @static
1623 * @public
1624 */
1625 static function countryIDForStateID($stateID) {
1626 if (empty($stateID)) {
1627 return CRM_Core_DAO::$_nullObject;
1628 }
1629
1630 $query = "
1631 SELECT country_id
1632 FROM civicrm_state_province
1633 WHERE id = %1
1634 ";
1635 $params = array(1 => array($stateID, 'Integer'));
1636
1637 return CRM_Core_DAO::singleValueQuery($query, $params);
1638 }
1639
1640 /**
1641 * Get all types of Greetings.
1642 *
1643 * The static array of greeting is returned
1644 *
1645 * @access public
1646 * @static
1647 *
1648 * @param $filter - get All Email Greetings - default is to get only active ones.
1649 *
1650 * @return array - array reference of all greetings.
1651 *
1652 */
1653 public static function greeting($filter, $columnName = 'label') {
1654 $index = $filter['greeting_type'] . '_' . $columnName;
1655
1656 // also add contactType to the array
1657 $contactType = CRM_Utils_Array::value('contact_type', $filter);
1658 if ($contactType) {
1659 $index .= '_' . $contactType;
1660 }
1661
1662 if (NULL === self::$greeting) {
1663 self::$greeting = array();
1664 }
1665
1666 if (!CRM_Utils_Array::value($index, self::$greeting)) {
1667 $filterCondition = NULL;
1668 if ($contactType) {
1669 $filterVal = 'v.filter =';
1670 switch ($contactType) {
1671 case 'Individual':
1672 $filterVal .= "1";
1673 break;
1674
1675 case 'Household':
1676 $filterVal .= "2";
1677 break;
1678
1679 case 'Organization':
1680 $filterVal .= "3";
1681 break;
1682 }
1683 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1684 }
1685
1686 self::$greeting[$index] = CRM_Core_OptionGroup::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1687 }
1688
1689 return self::$greeting[$index];
1690 }
1691
1692 /**
1693 * Construct array of default greeting values for contact type
1694 *
1695 * @access public
1696 * @static
1697 *
1698 * @return array - array reference of default greetings.
1699 *
1700 */
1701 public static function &greetingDefaults() {
1702 if (!self::$greetingDefaults) {
1703 $defaultGreetings = array();
1704 $contactTypes = self::get('CRM_Contact_DAO_Contact', 'contact_type', array('keyColumn' => 'id', 'labelColumn' => 'name'));
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 * @access public
1730 * @static
1731 *
1732 * @return array - array($fullyQualifiedName => $label) list of extensions
1733 */
1734 public static function &getExtensions() {
1735 if (!self::$extensions) {
1736 self::$extensions = array();
1737 $sql = '
1738 SELECT full_name, label
1739 FROM civicrm_extension
1740 WHERE is_active = 1
1741 ';
1742 $dao = CRM_Core_DAO::executeQuery($sql);
1743 while ($dao->fetch()) {
1744 self::$extensions[$dao->full_name] = $dao->label;
1745 }
1746 }
1747
1748 return self::$extensions;
1749 }
1750
1751 /**
1752 * Get all options values
1753 *
1754 * The static array option values is returned
1755 *
1756 * @access public
1757 * @static
1758 *
1759 * @param boolean $optionGroupName - get All Option Group values- default is to get only active ones.
1760 *
1761 * @return array - array reference of all Option Group Name
1762 *
1763 */
1764 public static function accountOptionValues($optionGroupName, $id = null, $condition = null) {
1765 $cacheKey = $optionGroupName . '_' . $condition;
1766 if (empty(self::$accountOptionValues[$cacheKey])) {
1767 self::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup::values($optionGroupName, false, false, false, $condition);
1768 }
1769 if ($id) {
1770 return CRM_Utils_Array::value($id, self::$accountOptionValues[$cacheKey]);
1771 }
1772
1773 return self::$accountOptionValues[$cacheKey];
1774 }
1775
1776 /**
1777 * Fetch the list of active extensions of type 'module'
1778 *
1779 * @param $fresh bool whether to forcibly reload extensions list from canonical store
1780 * @access public
1781 * @static
1782 *
1783 * @return array - array(array('prefix' => $, 'file' => $))
1784 */
1785 public static function getModuleExtensions($fresh = FALSE) {
1786 return CRM_Extension_System::singleton()->getMapper()->getActiveModuleFiles($fresh);
1787 }
1788 }
1789