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