Merge pull request #3209 from eileenmcnaughton/comments
[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 boolean $name pseudoconstant to be flushed
603 *
604 */
605 public static function flush($name = 'cache') {
606 if (isset(self::$$name)) {
607 self::$$name = NULL;
608 }
609 if ($name == 'cache') {
610 CRM_Core_OptionGroup::flushAll();
611 }
612 }
613
614 /**
615 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
616 *
617 * Get all Activty types.
618 *
619 * The static array activityType is returned
620 *
621 * @param boolean $all - get All Activity types - default is to get only active ones.
622 *
623 * @access public
624 * @static
625 *
626 * @return array - array reference of all activity types.
627 */
628 public static function &activityType() {
629 $args = func_get_args();
630 $all = CRM_Utils_Array::value(0, $args, TRUE);
631 $includeCaseActivities = CRM_Utils_Array::value(1, $args, FALSE);
632 $reset = CRM_Utils_Array::value(2, $args, FALSE);
633 $returnColumn = CRM_Utils_Array::value(3, $args, 'label');
634 $includeCampaignActivities = CRM_Utils_Array::value(4, $args, FALSE);
635 $onlyComponentActivities = CRM_Utils_Array::value(5, $args, FALSE);
636 $index = (int) $all . '_' . $returnColumn . '_' . (int) $includeCaseActivities;
637 $index .= '_' . (int) $includeCampaignActivities;
638 $index .= '_' . (int) $onlyComponentActivities;
639
640 if (NULL === self::$activityType) {
641 self::$activityType = array();
642 }
643
644 if (!isset(self::$activityType[$index]) || $reset) {
645 $condition = NULL;
646 if (!$all) {
647 $condition = 'AND filter = 0';
648 }
649 $componentClause = " v.component_id IS NULL";
650 if ($onlyComponentActivities) {
651 $componentClause = " v.component_id IS NOT NULL";
652 }
653
654 $componentIds = array();
655 $compInfo = CRM_Core_Component::getEnabledComponents();
656
657 // build filter for listing activity types only if their
658 // respective components are enabled
659 foreach ($compInfo as $compName => $compObj) {
660 if ($compName == 'CiviCase') {
661 if ($includeCaseActivities) {
662 $componentIds[] = $compObj->componentID;
663 }
664 }
665 elseif ($compName == 'CiviCampaign') {
666 if ($includeCampaignActivities) {
667 $componentIds[] = $compObj->componentID;
668 }
669 }
670 else {
671 $componentIds[] = $compObj->componentID;
672 }
673 }
674
675 if (count($componentIds)) {
676 $componentIds = implode(',', $componentIds);
677 $componentClause = " ($componentClause OR v.component_id IN ($componentIds))";
678 if ($onlyComponentActivities) {
679 $componentClause = " ( v.component_id IN ($componentIds ) )";
680 }
681 }
682 $condition = $condition . ' AND ' . $componentClause;
683
684 self::$activityType[$index] = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, $condition, $returnColumn);
685 }
686 return self::$activityType[$index];
687 }
688
689 /**
690 * Get all the State/Province from database.
691 *
692 * The static array stateProvince is returned, and if it's
693 * called the first time, the <b>State Province DAO</b> is used
694 * to get all the States.
695 *
696 * Note: any database errors will be trapped by the DAO.
697 *
698 * @access public
699 * @static
700 *
701 * @param int $id - Optional id to return
702 *
703 * @return array - array reference of all State/Provinces.
704 *
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 int $id - Optional id to return
757 *
758 * @return array - array reference of all State/Province abbreviations.
759 */
760 public static function &stateProvinceAbbreviation($id = FALSE, $limit = TRUE) {
761 if ($id > 1) {
762 $query = "
763 SELECT abbreviation
764 FROM civicrm_state_province
765 WHERE id = %1";
766 $params = array(
767 1 => array(
768 $id,
769 'Integer',
770 ),
771 );
772 return CRM_Core_DAO::singleValueQuery($query, $params);
773 }
774
775 if (!self::$stateProvinceAbbreviation || !$id) {
776
777 $whereClause = FALSE;
778
779 if ($limit) {
780 $config = CRM_Core_Config::singleton();
781 $countryIsoCodes = self::countryIsoCode();
782 $limitCodes = $config->provinceLimit();
783 $limitIds = array();
784 foreach ($limitCodes as $code) {
785 $tmpArray = array_keys($countryIsoCodes, $code);
786
787 if (!empty($tmpArray)) {
788 $limitIds[] = array_shift($tmpArray);
789 }
790 }
791 if (!empty($limitIds)) {
792 $whereClause = 'country_id IN (' . implode(', ', $limitIds) . ')';
793 }
794 }
795 self::populate(self::$stateProvinceAbbreviation, 'CRM_Core_DAO_StateProvince', TRUE, 'abbreviation', 'is_active', $whereClause);
796 }
797
798 if ($id) {
799 if (array_key_exists($id, self::$stateProvinceAbbreviation)) {
800 return self::$stateProvinceAbbreviation[$id];
801 }
802 else {
803 $result = NULL;
804 return $result;
805 }
806 }
807 return self::$stateProvinceAbbreviation;
808 }
809
810 /**
811 * Get all the countries from database.
812 *
813 * The static array country is returned, and if it's
814 * called the first time, the <b>Country DAO</b> is used
815 * to get all the countries.
816 *
817 * Note: any database errors will be trapped by the DAO.
818 *
819 * @access public
820 * @static
821 *
822 * @param int $id - Optional id to return
823 *
824 * @return array - array reference of all countries.
825 *
826 */
827 public static function country($id = FALSE, $applyLimit = TRUE) {
828 if (($id && !CRM_Utils_Array::value($id, self::$country)) || !self::$country || !$id) {
829
830 $config = CRM_Core_Config::singleton();
831 $limitCodes = array();
832
833 if ($applyLimit) {
834 // limit the country list to the countries specified in CIVICRM_COUNTRY_LIMIT
835 // (ensuring it's a subset of the legal values)
836 // K/P: We need to fix this, i dont think it works with new setting files
837 $limitCodes = $config->countryLimit();
838 if (!is_array($limitCodes)) {
839 $limitCodes = array(
840 $config->countryLimit => 1,
841 );
842 }
843
844 $limitCodes = array_intersect(self::countryIsoCode(), $limitCodes);
845 }
846
847 if (count($limitCodes)) {
848 $whereClause = "iso_code IN ('" . implode("', '", $limitCodes) . "')";
849 }
850 else {
851 $whereClause = NULL;
852 }
853
854 self::populate(self::$country, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active', $whereClause);
855
856 // if default country is set, percolate it to the top
857 if ($config->defaultContactCountry()) {
858 $countryIsoCodes = self::countryIsoCode();
859 $defaultID = array_search($config->defaultContactCountry(), $countryIsoCodes);
860 if ($defaultID !== FALSE) {
861 $default[$defaultID] = CRM_Utils_Array::value($defaultID, self::$country);
862 self::$country = $default + self::$country;
863 }
864 }
865
866 // localise the country names if in an non-en_US locale
867 global $tsLocale;
868 if ($tsLocale != '' and $tsLocale != 'en_US') {
869 $i18n = CRM_Core_I18n::singleton();
870 $i18n->localizeArray(self::$country, array(
871 'context' => 'country',
872 ));
873 self::$country = CRM_Utils_Array::asort(self::$country);
874 }
875 }
876 if ($id) {
877 if (array_key_exists($id, self::$country)) {
878 return self::$country[$id];
879 }
880 else {
881 return CRM_Core_DAO::$_nullObject;
882 }
883 }
884 return self::$country;
885 }
886
887 /**
888 * Get all the country ISO Code abbreviations from the database.
889 *
890 * The static array countryIsoCode is returned, and if it's
891 * called the first time, the <b>Country DAO</b> is used
892 * to get all the countries' ISO codes.
893 *
894 * Note: any database errors will be trapped by the DAO.
895 *
896 * @access public
897 * @static
898 *
899 * @return array - array reference of all country ISO codes.
900 *
901 */
902 public static function &countryIsoCode($id = FALSE) {
903 if (!self::$countryIsoCode) {
904 self::populate(self::$countryIsoCode, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
905 }
906 if ($id) {
907 if (array_key_exists($id, self::$countryIsoCode)) {
908 return self::$countryIsoCode[$id];
909 }
910 else {
911 return CRM_Core_DAO::$_nullObject;
912 }
913 }
914 return self::$countryIsoCode;
915 }
916
917 /**
918 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
919 *
920 * Get all groups from database
921 *
922 * The static array group is returned, and if it's
923 * called the first time, the <b>Group DAO</b> is used
924 * to get all the groups.
925 *
926 * Note: any database errors will be trapped by the DAO.
927 *
928 * @param string $groupType type of group(Access/Mailing)
929 * @param boolen $excludeHidden exclude hidden groups.
930 *
931 * @access public
932 * @static
933 *
934 * @return array - array reference of all groups.
935 *
936 */
937 public static function &allGroup($groupType = NULL, $excludeHidden = TRUE) {
938 $condition = CRM_Contact_BAO_Group::groupTypeCondition($groupType, $excludeHidden);
939
940 if (!self::$group) {
941 self::$group = array();
942 }
943
944 $groupKey = $groupType ? $groupType : 'null';
945
946 if (!isset(self::$group[$groupKey])) {
947 self::$group[$groupKey] = NULL;
948 self::populate(self::$group[$groupKey], 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition);
949 }
950 return self::$group[$groupKey];
951 }
952
953 /**
954 * Create or get groups iterator (iterates over nested groups in a
955 * logical fashion)
956 *
957 * The GroupNesting instance is returned; it's created if this is being
958 * called for the first time
959 *
960 *
961 * @access public
962 * @static
963 *
964 * @return mixed - instance of CRM_Contact_BAO_GroupNesting
965 *
966 */
967 public static function &groupIterator($styledLabels = FALSE) {
968 if (!self::$groupIterator) {
969 /*
970 When used as an object, GroupNesting implements Iterator
971 and iterates nested groups in a logical manner for us
972 */
973 self::$groupIterator = new CRM_Contact_BAO_GroupNesting($styledLabels);
974 }
975 return self::$groupIterator;
976 }
977
978 /**
979 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
980 *
981 * Get all permissioned groups from database
982 *
983 * The static array group is returned, and if it's
984 * called the first time, the <b>Group DAO</b> is used
985 * to get all the groups.
986 *
987 * Note: any database errors will be trapped by the DAO.
988 *
989 * @param string $groupType type of group(Access/Mailing)
990 * @param boolen $excludeHidden exclude hidden groups.
991
992 * @access public
993 * @static
994 *
995 * @return array - array reference of all groups.
996 *
997 */
998 public static function group($groupType = NULL, $excludeHidden = TRUE) {
999 return CRM_Core_Permission::group($groupType, $excludeHidden);
1000 }
1001
1002 /**
1003 * Get all permissioned groups from database
1004 *
1005 * The static array group is returned, and if it's
1006 * called the first time, the <b>Group DAO</b> is used
1007 * to get all the groups.
1008 *
1009 * Note: any database errors will be trapped by the DAO.
1010 *
1011 * @access public
1012 * @static
1013 *
1014 * @return array - array reference of all groups.
1015 *
1016 */
1017 public static function &staticGroup($onlyPublic = FALSE, $groupType = NULL, $excludeHidden = TRUE) {
1018 if (!self::$staticGroup) {
1019 $condition = 'saved_search_id = 0 OR saved_search_id IS NULL';
1020 if ($onlyPublic) {
1021 $condition .= " AND visibility != 'User and User Admin Only'";
1022 }
1023
1024 if ($groupType) {
1025 $condition .= ' AND ' . CRM_Contact_BAO_Group::groupTypeCondition($groupType);
1026 }
1027
1028 if ($excludeHidden) {
1029 $condition .= ' AND is_hidden != 1 ';
1030 }
1031
1032 self::populate(self::$staticGroup, 'CRM_Contact_DAO_Group', FALSE, 'title', 'is_active', $condition, 'title');
1033 }
1034
1035 return self::$staticGroup;
1036 }
1037
1038 /**
1039 * Get all Relationship Types from database.
1040 *
1041 * The static array group is returned, and if it's
1042 * called the first time, the <b>RelationshipType DAO</b> is used
1043 * to get all the relationship types.
1044 *
1045 * Note: any database errors will be trapped by the DAO.
1046 *
1047 * @param string $valueColumnName db column name/label.
1048 * @param boolean $reset reset relationship types if true
1049 *
1050 * @access public
1051 * @static
1052 *
1053 * @return array - array reference of all relationship types.
1054 */
1055 public static function &relationshipType($valueColumnName = 'label', $reset = FALSE) {
1056 if (!CRM_Utils_Array::value($valueColumnName, self::$relationshipType) || $reset) {
1057 self::$relationshipType[$valueColumnName] = array();
1058
1059 //now we have name/label columns CRM-3336
1060 $column_a_b = "{$valueColumnName}_a_b";
1061 $column_b_a = "{$valueColumnName}_b_a";
1062
1063 $relationshipTypeDAO = new CRM_Contact_DAO_RelationshipType();
1064 $relationshipTypeDAO->selectAdd();
1065 $relationshipTypeDAO->selectAdd("id, {$column_a_b}, {$column_b_a}, contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b");
1066 $relationshipTypeDAO->is_active = 1;
1067 $relationshipTypeDAO->find();
1068 while ($relationshipTypeDAO->fetch()) {
1069
1070 self::$relationshipType[$valueColumnName][$relationshipTypeDAO->id] = array(
1071 'id' => $relationshipTypeDAO->id,
1072 $column_a_b => $relationshipTypeDAO->$column_a_b,
1073 $column_b_a => $relationshipTypeDAO->$column_b_a,
1074 'contact_type_a' => "$relationshipTypeDAO->contact_type_a",
1075 'contact_type_b' => "$relationshipTypeDAO->contact_type_b",
1076 'contact_sub_type_a' => "$relationshipTypeDAO->contact_sub_type_a",
1077 'contact_sub_type_b' => "$relationshipTypeDAO->contact_sub_type_b",
1078 );
1079 }
1080 }
1081
1082 return self::$relationshipType[$valueColumnName];
1083 }
1084
1085 /**
1086 * get all the ISO 4217 currency codes
1087 *
1088 * so far, we use this for validation only, so there's no point of putting this into the database
1089 *
1090 * @access public
1091 *
1092 * @return array - array reference of all currency codes
1093 * @static
1094 */
1095 public static function &currencyCode() {
1096 if (!self::$currencyCode) {
1097 self::$currencyCode = array(
1098 'AFN',
1099 'ALL',
1100 'DZD',
1101 'USD',
1102 'EUR',
1103 'AOA',
1104 'XCD',
1105 'XCD',
1106 'ARS',
1107 'AMD',
1108 'AWG',
1109 'AUD',
1110 'EUR',
1111 'AZM',
1112 'BSD',
1113 'BHD',
1114 'BDT',
1115 'BBD',
1116 'BYR',
1117 'EUR',
1118 'BZD',
1119 'XOF',
1120 'BMD',
1121 'INR',
1122 'BTN',
1123 'BOB',
1124 'BOV',
1125 'BAM',
1126 'BWP',
1127 'NOK',
1128 'BRL',
1129 'USD',
1130 'BND',
1131 'BGN',
1132 'XOF',
1133 'BIF',
1134 'KHR',
1135 'XAF',
1136 'CAD',
1137 'CVE',
1138 'KYD',
1139 'XAF',
1140 'XAF',
1141 'CLP',
1142 'CLF',
1143 'CNY',
1144 'AUD',
1145 'AUD',
1146 'COP',
1147 'COU',
1148 'KMF',
1149 'XAF',
1150 'CDF',
1151 'NZD',
1152 'CRC',
1153 'XOF',
1154 'HRK',
1155 'CUP',
1156 'CYP',
1157 'CZK',
1158 'DKK',
1159 'DJF',
1160 'XCD',
1161 'DOP',
1162 'USD',
1163 'EGP',
1164 'SVC',
1165 'USD',
1166 'XAF',
1167 'ERN',
1168 'EEK',
1169 'ETB',
1170 'FKP',
1171 'DKK',
1172 'FJD',
1173 'EUR',
1174 'EUR',
1175 'EUR',
1176 'XPF',
1177 'EUR',
1178 'XAF',
1179 'GMD',
1180 'GEL',
1181 'EUR',
1182 'GHC',
1183 'GIP',
1184 'EUR',
1185 'DKK',
1186 'XCD',
1187 'EUR',
1188 'USD',
1189 'GTQ',
1190 'GNF',
1191 'GWP',
1192 'XOF',
1193 'GYD',
1194 'HTG',
1195 'USD',
1196 'AUD',
1197 'EUR',
1198 'HNL',
1199 'HKD',
1200 'HUF',
1201 'ISK',
1202 'INR',
1203 'IDR',
1204 'XDR',
1205 'IRR',
1206 'IQD',
1207 'EUR',
1208 'ILS',
1209 'EUR',
1210 'JMD',
1211 'JPY',
1212 'JOD',
1213 'KZT',
1214 'KES',
1215 'AUD',
1216 'KPW',
1217 'KRW',
1218 'KWD',
1219 'KGS',
1220 'LAK',
1221 'LVL',
1222 'LBP',
1223 'ZAR',
1224 'LSL',
1225 'LRD',
1226 'LYD',
1227 'CHF',
1228 'LTL',
1229 'EUR',
1230 'MOP',
1231 'MKD',
1232 'MGA',
1233 'MWK',
1234 'MYR',
1235 'MVR',
1236 'XOF',
1237 'MTL',
1238 'USD',
1239 'EUR',
1240 'MRO',
1241 'MUR',
1242 'EUR',
1243 'MXN',
1244 'MXV',
1245 'USD',
1246 'MDL',
1247 'EUR',
1248 'MNT',
1249 'XCD',
1250 'MAD',
1251 'MZM',
1252 'MMK',
1253 'ZAR',
1254 'NAD',
1255 'AUD',
1256 'NPR',
1257 'EUR',
1258 'ANG',
1259 'XPF',
1260 'NZD',
1261 'NIO',
1262 'XOF',
1263 'NGN',
1264 'NZD',
1265 'AUD',
1266 'USD',
1267 'NOK',
1268 'OMR',
1269 'PKR',
1270 'USD',
1271 'PAB',
1272 'USD',
1273 'PGK',
1274 'PYG',
1275 'PEN',
1276 'PHP',
1277 'NZD',
1278 'PLN',
1279 'EUR',
1280 'USD',
1281 'QAR',
1282 'EUR',
1283 'ROL',
1284 'RON',
1285 'RUB',
1286 'RWF',
1287 'SHP',
1288 'XCD',
1289 'XCD',
1290 'EUR',
1291 'XCD',
1292 'WST',
1293 'EUR',
1294 'STD',
1295 'SAR',
1296 'XOF',
1297 'CSD',
1298 'EUR',
1299 'SCR',
1300 'SLL',
1301 'SGD',
1302 'SKK',
1303 'SIT',
1304 'SBD',
1305 'SOS',
1306 'ZAR',
1307 'EUR',
1308 'LKR',
1309 'SDD',
1310 'SRD',
1311 'NOK',
1312 'SZL',
1313 'SEK',
1314 'CHF',
1315 'CHW',
1316 'CHE',
1317 'SYP',
1318 'TWD',
1319 'TJS',
1320 'TZS',
1321 'THB',
1322 'USD',
1323 'XOF',
1324 'NZD',
1325 'TOP',
1326 'TTD',
1327 'TND',
1328 'TRY',
1329 'TRL',
1330 'TMM',
1331 'USD',
1332 'AUD',
1333 'UGX',
1334 'UAH',
1335 'AED',
1336 'GBP',
1337 'USD',
1338 'USS',
1339 'USN',
1340 'USD',
1341 'UYU',
1342 'UZS',
1343 'VUV',
1344 'VEB',
1345 'VND',
1346 'USD',
1347 'USD',
1348 'XPF',
1349 'MAD',
1350 'YER',
1351 'ZMK',
1352 'ZWD',
1353 'XAU',
1354 'XBA',
1355 'XBB',
1356 'XBC',
1357 'XBD',
1358 'XPD',
1359 'XPT',
1360 'XAG',
1361 'XFU',
1362 'XFO',
1363 'XTS',
1364 'XXX',
1365 );
1366 }
1367 return self::$currencyCode;
1368 }
1369
1370 /**
1371 * Get all the County from database.
1372 *
1373 * The static array county is returned, and if it's
1374 * called the first time, the <b>County DAO</b> is used
1375 * to get all the Counties.
1376 *
1377 * Note: any database errors will be trapped by the DAO.
1378 *
1379 * @access public
1380 * @static
1381 *
1382 * @param bool|int $id - Optional id to return
1383 *
1384 * @return array - array reference of all Counties
1385 */
1386 public static function &county($id = FALSE) {
1387 if (!self::$county) {
1388
1389 $config = CRM_Core_Config::singleton();
1390 // order by id so users who populate civicrm_county can have more control over sort by the order they load the counties
1391 self::populate(self::$county, 'CRM_Core_DAO_County', TRUE, 'name', NULL, NULL, 'id');
1392 }
1393 if ($id) {
1394 if (array_key_exists($id, self::$county)) {
1395 return self::$county[$id];
1396 }
1397 else {
1398 return CRM_Core_DAO::$_nullObject;
1399 }
1400 }
1401 return self::$county;
1402 }
1403
1404 /**
1405 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
1406 * Get all active payment processors
1407 *
1408 * The static array paymentProcessor is returned
1409 *
1410 * @access public
1411 * @static
1412 *
1413 * @param boolean $all - get payment processors - default is to get only active ones.
1414 * @param boolean $test - get test payment processors
1415 *
1416 * @param null $additionalCond
1417 *
1418 * @return array - array of all payment processors
1419 */
1420 public static function &paymentProcessor($all = FALSE, $test = FALSE, $additionalCond = NULL) {
1421 $condition = "is_test = ";
1422 $condition .= ($test) ? '1' : '0';
1423
1424 if ($additionalCond) {
1425 $condition .= " AND ( $additionalCond ) ";
1426 }
1427
1428 // CRM-7178. Make sure we only include payment processors valid in ths
1429 // domain
1430 $condition .= " AND domain_id = " . CRM_Core_Config::domainID();
1431
1432 $cacheKey = $condition . '_' . (int) $all;
1433 if (!isset(self::$paymentProcessor[$cacheKey])) {
1434 self::populate(self::$paymentProcessor[$cacheKey], 'CRM_Financial_DAO_PaymentProcessor', $all, 'name', 'is_active', $condition, 'is_default desc, name');
1435 }
1436
1437 return self::$paymentProcessor[$cacheKey];
1438 }
1439
1440 /**
1441 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
1442 *
1443 * The static array paymentProcessorType is returned
1444 *
1445 * @access public
1446 * @static
1447 *
1448 * @param boolean $all - get payment processors - default is to get only active ones.
1449 *
1450 * @param null $id
1451 * @param string $return
1452 *
1453 * @return array - array of all payment processor types
1454 */
1455 public static function &paymentProcessorType($all = FALSE, $id = NULL, $return = 'title') {
1456 $cacheKey = $id . '_' .$return;
1457 if (empty(self::$paymentProcessorType[$cacheKey])) {
1458 self::populate(self::$paymentProcessorType[$cacheKey], 'CRM_Financial_DAO_PaymentProcessorType', $all, $return, 'is_active', NULL, "is_default, $return", 'id');
1459 }
1460 if ($id && CRM_Utils_Array::value($id, self::$paymentProcessorType[$cacheKey])) {
1461 return self::$paymentProcessorType[$cacheKey][$id];
1462 }
1463 return self::$paymentProcessorType[$cacheKey];
1464 }
1465
1466 /**
1467 * Get all the World Regions from Database
1468 *
1469 * @access public
1470 *
1471 * @param bool $id
1472 *
1473 * @return array - array reference of all World Regions
1474 * @static
1475 */
1476 public static function &worldRegion($id = FALSE) {
1477 if (!self::$worldRegions) {
1478 self::populate(self::$worldRegions, 'CRM_Core_DAO_Worldregion', TRUE, 'name', NULL, NULL, 'id');
1479 }
1480
1481 if ($id) {
1482 if (array_key_exists($id, self::$worldRegions)) {
1483 return self::$worldRegions[$id];
1484 }
1485 else {
1486 return CRM_Core_DAO::$_nullObject;
1487 }
1488 }
1489
1490 return self::$worldRegions;
1491 }
1492
1493 /**
1494 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
1495 *
1496 * Get all Activity Statuses.
1497 *
1498 * The static array activityStatus is returned
1499 *
1500 * @access public
1501 * @static
1502 *
1503 * @param string $column
1504 *
1505 * @return array - array reference of all activity statuses
1506 */
1507 public static function &activityStatus($column = 'label') {
1508 if (NULL === self::$activityStatus) {
1509 self::$activityStatus = array();
1510 }
1511 if (!array_key_exists($column, self::$activityStatus)) {
1512 self::$activityStatus[$column] = array();
1513
1514 self::$activityStatus[$column] = CRM_Core_OptionGroup::values('activity_status', FALSE, FALSE, FALSE, NULL, $column);
1515 }
1516
1517 return self::$activityStatus[$column];
1518 }
1519
1520 /**
1521 * DEPRECATED. Please use the buildOptions() method in the appropriate BAO object.
1522 *
1523 * Get all Visibility levels.
1524 *
1525 * The static array visibility is returned
1526 *
1527 * @access public
1528 * @static
1529 *
1530 * @param string $column
1531 *
1532 * @return array - array reference of all Visibility levels.
1533 */
1534 public static function &visibility($column = 'label') {
1535 if (!isset(self::$visibility)) {
1536 self::$visibility = array( );
1537 }
1538
1539 if (!isset(self::$visibility[$column])) {
1540 self::$visibility[$column] = CRM_Core_OptionGroup::values('visibility', FALSE, FALSE, FALSE, NULL, $column);
1541 }
1542
1543 return self::$visibility[$column];
1544 }
1545
1546 public static function &stateProvinceForCountry($countryID, $field = 'name') {
1547 static $_cache = NULL;
1548
1549 $cacheKey = "{$countryID}_{$field}";
1550 if (!$_cache) {
1551 $_cache = array();
1552 }
1553
1554 if (!empty($_cache[$cacheKey])) {
1555 return $_cache[$cacheKey];
1556 }
1557
1558 $query = "
1559 SELECT civicrm_state_province.{$field} name, civicrm_state_province.id id
1560 FROM civicrm_state_province
1561 WHERE country_id = %1
1562 ORDER BY name";
1563 $params = array(
1564 1 => array(
1565 $countryID,
1566 'Integer',
1567 ),
1568 );
1569
1570 $dao = CRM_Core_DAO::executeQuery($query, $params);
1571
1572 $result = array();
1573 while ($dao->fetch()) {
1574 $result[$dao->id] = $dao->name;
1575 }
1576
1577 // localise the stateProvince names if in an non-en_US locale
1578 $config = CRM_Core_Config::singleton();
1579 global $tsLocale;
1580 if ($tsLocale != '' and $tsLocale != 'en_US') {
1581 $i18n = CRM_Core_I18n::singleton();
1582 $i18n->localizeArray($result, array(
1583 'context' => 'province',
1584 ));
1585 $result = CRM_Utils_Array::asort($result);
1586 }
1587
1588 $_cache[$cacheKey] = $result;
1589
1590 CRM_Utils_Hook::buildStateProvinceForCountry($countryID, $result);
1591
1592 return $result;
1593 }
1594
1595 public static function &countyForState($stateID) {
1596 if (is_array($stateID)) {
1597 $states = implode(", ", $stateID);
1598 $query = "
1599 SELECT civicrm_county.name name, civicrm_county.id id, civicrm_state_province.abbreviation abbreviation
1600 FROM civicrm_county
1601 LEFT JOIN civicrm_state_province ON civicrm_county.state_province_id = civicrm_state_province.id
1602 WHERE civicrm_county.state_province_id in ( $states )
1603 ORDER BY civicrm_state_province.abbreviation, civicrm_county.name";
1604
1605 $dao = CRM_Core_DAO::executeQuery($query);
1606
1607 $result = array();
1608 while ($dao->fetch()) {
1609 $result[$dao->id] = $dao->abbreviation . ': ' . $dao->name;
1610 }
1611 }
1612 else {
1613
1614 static $_cache = NULL;
1615
1616 $cacheKey = "{$stateID}_name";
1617 if (!$_cache) {
1618 $_cache = array();
1619 }
1620
1621 if (!empty($_cache[$cacheKey])) {
1622 return $_cache[$cacheKey];
1623 }
1624
1625 $query = "
1626 SELECT civicrm_county.name name, civicrm_county.id id
1627 FROM civicrm_county
1628 WHERE state_province_id = %1
1629 ORDER BY name";
1630 $params = array(
1631 1 => array(
1632 $stateID,
1633 'Integer',
1634 ),
1635 );
1636
1637 $dao = CRM_Core_DAO::executeQuery($query, $params);
1638
1639 $result = array();
1640 while ($dao->fetch()) {
1641 $result[$dao->id] = $dao->name;
1642 }
1643 }
1644
1645 return $result;
1646 }
1647
1648 /**
1649 * Given a state ID return the country ID, this allows
1650 * us to populate forms and values for downstream code
1651 *
1652 * @param $stateID int
1653 *
1654 * @return int the country id that the state belongs to
1655 * @static
1656 * @public
1657 */
1658 static function countryIDForStateID($stateID) {
1659 if (empty($stateID)) {
1660 return CRM_Core_DAO::$_nullObject;
1661 }
1662
1663 $query = "
1664 SELECT country_id
1665 FROM civicrm_state_province
1666 WHERE id = %1
1667 ";
1668 $params = array(1 => array($stateID, 'Integer'));
1669
1670 return CRM_Core_DAO::singleValueQuery($query, $params);
1671 }
1672
1673 /**
1674 * Get all types of Greetings.
1675 *
1676 * The static array of greeting is returned
1677 *
1678 * @access public
1679 * @static
1680 *
1681 * @param $filter - get All Email Greetings - default is to get only active ones.
1682 *
1683 * @param string $columnName
1684 *
1685 * @return array - array reference of all greetings.
1686 */
1687 public static function greeting($filter, $columnName = 'label') {
1688 $index = $filter['greeting_type'] . '_' . $columnName;
1689
1690 // also add contactType to the array
1691 $contactType = CRM_Utils_Array::value('contact_type', $filter);
1692 if ($contactType) {
1693 $index .= '_' . $contactType;
1694 }
1695
1696 if (NULL === self::$greeting) {
1697 self::$greeting = array();
1698 }
1699
1700 if (!CRM_Utils_Array::value($index, self::$greeting)) {
1701 $filterCondition = NULL;
1702 if ($contactType) {
1703 $filterVal = 'v.filter =';
1704 switch ($contactType) {
1705 case 'Individual':
1706 $filterVal .= "1";
1707 break;
1708
1709 case 'Household':
1710 $filterVal .= "2";
1711 break;
1712
1713 case 'Organization':
1714 $filterVal .= "3";
1715 break;
1716 }
1717 $filterCondition .= "AND (v.filter = 0 OR {$filterVal}) ";
1718 }
1719
1720 self::$greeting[$index] = CRM_Core_OptionGroup::values($filter['greeting_type'], NULL, NULL, NULL, $filterCondition, $columnName);
1721 }
1722
1723 return self::$greeting[$index];
1724 }
1725
1726 /**
1727 * Construct array of default greeting values for contact type
1728 *
1729 * @access public
1730 * @static
1731 *
1732 * @return array - array reference of default greetings.
1733 *
1734 */
1735 public static function &greetingDefaults() {
1736 if (!self::$greetingDefaults) {
1737 $defaultGreetings = array();
1738 $contactTypes = self::get('CRM_Contact_DAO_Contact', 'contact_type', array('keyColumn' => 'id', 'labelColumn' => 'name'));
1739
1740 foreach ($contactTypes as $filter => $contactType) {
1741 $filterCondition = " AND (v.filter = 0 OR v.filter = $filter) AND v.is_default = 1 ";
1742
1743 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
1744 $tokenVal = CRM_Core_OptionGroup::values($greeting, NULL, NULL, NULL, $filterCondition, 'label');
1745 $defaultGreetings[$contactType][$greeting] = $tokenVal;
1746 }
1747 }
1748
1749 self::$greetingDefaults = $defaultGreetings;
1750 }
1751
1752 return self::$greetingDefaults;
1753 }
1754
1755 /**
1756 * Get all extensions
1757 *
1758 * The static array extensions
1759 *
1760 * FIXME: This is called by civix but not by any core code. We
1761 * should provide an API call which civix can use instead.
1762 *
1763 * @access public
1764 * @static
1765 *
1766 * @return array - array($fullyQualifiedName => $label) list of extensions
1767 */
1768 public static function &getExtensions() {
1769 if (!self::$extensions) {
1770 self::$extensions = array();
1771 $sql = '
1772 SELECT full_name, label
1773 FROM civicrm_extension
1774 WHERE is_active = 1
1775 ';
1776 $dao = CRM_Core_DAO::executeQuery($sql);
1777 while ($dao->fetch()) {
1778 self::$extensions[$dao->full_name] = $dao->label;
1779 }
1780 }
1781
1782 return self::$extensions;
1783 }
1784
1785 /**
1786 * Get all options values
1787 *
1788 * The static array option values is returned
1789 *
1790 * @access public
1791 * @static
1792 *
1793 * @param boolean $optionGroupName - get All Option Group values- default is to get only active ones.
1794 *
1795 * @param null $id
1796 * @param null $condition
1797 *
1798 * @return array - array reference of all Option Group Name
1799 */
1800 public static function accountOptionValues($optionGroupName, $id = null, $condition = null) {
1801 $cacheKey = $optionGroupName . '_' . $condition;
1802 if (empty(self::$accountOptionValues[$cacheKey])) {
1803 self::$accountOptionValues[$cacheKey] = CRM_Core_OptionGroup::values($optionGroupName, false, false, false, $condition);
1804 }
1805 if ($id) {
1806 return CRM_Utils_Array::value($id, self::$accountOptionValues[$cacheKey]);
1807 }
1808
1809 return self::$accountOptionValues[$cacheKey];
1810 }
1811
1812 /**
1813 * Fetch the list of active extensions of type 'module'
1814 *
1815 * @param $fresh bool whether to forcibly reload extensions list from canonical store
1816 * @access public
1817 * @static
1818 *
1819 * @return array - array(array('prefix' => $, 'file' => $))
1820 */
1821 public static function getModuleExtensions($fresh = FALSE) {
1822 return CRM_Extension_System::singleton()->getMapper()->getActiveModuleFiles($fresh);
1823 }
1824 }
1825