3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2018
33 class CRM_Core_BAO_OptionValue
extends CRM_Core_DAO_OptionValue
{
38 public function __construct() {
39 parent
::__construct();
43 * Create option value.
45 * Note that the create function calls 'add' but has more business logic.
47 * @param array $params
52 public static function create($params) {
53 if (empty($params['id'])) {
54 self
::setDefaults($params);
57 if (!empty($params['id'])) {
58 $ids = array('optionValue' => $params['id']);
60 return CRM_Core_BAO_OptionValue
::add($params, $ids);
64 * Set default Parameters.
65 * This functions sets default parameters if not set:
66 * - name & label are set to each other as required (it might make more sense for one
67 * to be required but this would mean a change to the api level)
68 * - weight & value will be set to their respective option groups next values
69 * if nothing is passed in.
71 * Note this function does not check for presence of $params['id'] so should only be called
72 * if 'id' is not present
74 * @param array $params
76 public static function setDefaults(&$params) {
77 if (CRM_Utils_Array
::value('label', $params, NULL) === NULL) {
78 $params['label'] = $params['name'];
80 if (CRM_Utils_Array
::value('name', $params, NULL) === NULL) {
81 $params['name'] = $params['label'];
83 if (CRM_Utils_Array
::value('weight', $params, NULL) === NULL) {
84 $params['weight'] = self
::getDefaultWeight($params);
86 if (CRM_Utils_Array
::value('value', $params, NULL) === NULL) {
87 $params['value'] = self
::getDefaultValue($params);
92 * Get next available value.
93 * We will take the highest numeric value (or 0 if no numeric values exist)
94 * and add one. The calling function is responsible for any
95 * more complex decision making
97 * @param array $params
101 public static function getDefaultWeight($params) {
102 return (int) CRM_Utils_Weight
::getDefaultWeight('CRM_Core_DAO_OptionValue',
103 array('option_group_id' => $params['option_group_id']));
107 * Get next available value.
108 * We will take the highest numeric value (or 0 if no numeric values exist)
109 * and add one. The calling function is responsible for any
110 * more complex decision making
111 * @param array $params
113 public static function getDefaultValue($params) {
114 $bao = new CRM_Core_BAO_OptionValue();
115 $bao->option_group_id
= $params['option_group_id'];
116 if (isset($params['domain_id'])) {
117 $bao->domain_id
= $params['domain_id'];
120 $bao->whereAdd("value REGEXP '^[0-9]+$'");
121 $bao->selectAdd('(ROUND(COALESCE(MAX(CONVERT(value, UNSIGNED)),0)) +1) as nextvalue');
123 return $bao->nextvalue
;
127 * Fetch object based on array of properties.
129 * @param array $params
130 * (reference ) an assoc array of name/value pairs.
131 * @param array $defaults
132 * (reference ) an assoc array to hold the flattened values.
134 * @return CRM_Core_BAO_OptionValue
136 public static function retrieve(&$params, &$defaults) {
137 $optionValue = new CRM_Core_DAO_OptionValue();
138 $optionValue->copyValues($params);
139 if ($optionValue->find(TRUE)) {
140 CRM_Core_DAO
::storeValues($optionValue, $defaults);
147 * Update the is_active flag in the db.
150 * Id of the database record.
151 * @param bool $is_active
152 * Value we want to set the is_active field.
155 * DAO object on success, null otherwise
157 public static function setIsActive($id, $is_active) {
158 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_OptionValue', $id, 'is_active', $is_active);
162 * Add an Option Value.
164 * @param array $params
165 * Reference array contains the values submitted by the form.
167 * deprecated Reference array contains the id.
169 * @return \CRM_Core_DAO_OptionValue
170 * @throws \CRM_Core_Exception
172 public static function add(&$params, $ids = array()) {
173 $id = CRM_Utils_Array
::value('id', $params, CRM_Utils_Array
::value('optionValue', $ids));
174 // CRM-10921: do not reset attributes to default if this is an update
175 //@todo consider if defaults are being set in the right place. 'dumb' defaults like
176 // these would be usefully set @ the api layer so they are visible to api users
177 // complex defaults like the domain id below would make sense in the setDefauls function
178 // but unclear what other ways this function is being used
180 $params['is_active'] = CRM_Utils_Array
::value('is_active', $params, FALSE);
181 $params['is_default'] = CRM_Utils_Array
::value('is_default', $params, FALSE);
182 $params['is_optgroup'] = CRM_Utils_Array
::value('is_optgroup', $params, FALSE);
183 $params['filter'] = CRM_Utils_Array
::value('filter', $params, FALSE);
185 // Update custom field data to reflect the new value
186 elseif (isset($params['value'])) {
187 CRM_Core_BAO_CustomOption
::updateValue($id, $params['value']);
190 // We need to have option_group_id populated for validation so load if necessary.
191 if (empty($params['option_group_id'])) {
192 $params['option_group_id'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue',
193 $id, 'option_group_id', 'id'
196 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup',
197 $params['option_group_id'], 'name', 'id'
200 // action is taken depending upon the mode
201 $optionValue = new CRM_Core_DAO_OptionValue();
202 $optionValue->copyValues($params);
204 if (!empty($params['is_default'])) {
205 $query = 'UPDATE civicrm_option_value SET is_default = 0 WHERE option_group_id = %1';
207 // tweak default reset, and allow multiple default within group.
208 if ($resetDefaultFor = CRM_Utils_Array
::value('reset_default_for', $params)) {
209 if (is_array($resetDefaultFor)) {
210 $colName = key($resetDefaultFor);
211 $colVal = $resetDefaultFor[$colName];
212 $query .= " AND ( $colName IN ( $colVal ) )";
216 $p = array(1 => array($params['option_group_id'], 'Integer'));
217 CRM_Core_DAO
::executeQuery($query, $p);
220 if (empty($params['domain_id']) && in_array($groupName, CRM_Core_OptionGroup
::$_domainIDGroups)) {
221 $optionValue->domain_id
= CRM_Core_Config
::domainID();
224 $groupsSupportingDuplicateValues = ['languages'];
225 if (!$id && !empty($params['value'])) {
226 $dao = new CRM_Core_DAO_OptionValue();
227 if (!in_array($groupName, $groupsSupportingDuplicateValues)) {
228 $dao->value
= $params['value'];
231 // CRM-21737 languages option group does not use unique values but unique names.
232 $dao->name
= $params['name'];
234 if (in_array($groupName, CRM_Core_OptionGroup
::$_domainIDGroups)) {
235 $dao->domain_id
= $optionValue->domain_id
;
237 $dao->option_group_id
= $params['option_group_id'];
238 if ($dao->find(TRUE)) {
239 throw new CRM_Core_Exception('Value already exists in the database');
243 $optionValue->id
= $id;
244 $optionValue->save();
245 CRM_Core_PseudoConstant
::flush();
250 * Delete Option Value.
252 * @param int $optionValueId
257 public static function del($optionValueId) {
258 $optionValue = new CRM_Core_DAO_OptionValue();
259 $optionValue->id
= $optionValueId;
260 if (!$optionValue->find()) {
263 if (self
::updateRecords($optionValueId, CRM_Core_Action
::DELETE
)) {
264 CRM_Core_PseudoConstant
::flush();
265 $optionValue->delete();
272 * Retrieve activity type label and description.
274 * @param int $activityTypeId
278 * label and description
280 public static function getActivityTypeDetails($activityTypeId) {
281 $query = "SELECT civicrm_option_value.label, civicrm_option_value.description
282 FROM civicrm_option_value
283 LEFT JOIN civicrm_option_group ON ( civicrm_option_value.option_group_id = civicrm_option_group.id )
284 WHERE civicrm_option_group.name = 'activity_type'
285 AND civicrm_option_value.value = {$activityTypeId} ";
287 $dao = CRM_Core_DAO
::executeQuery($query);
291 return array($dao->label
, $dao->description
);
295 * Get the Option Value title.
298 * Id of Option Value.
304 public static function getTitle($id) {
305 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $id, 'label');
309 * Updates contacts affected by the option value passed.
311 * @param int $optionValueId
312 * The option value id.
314 * The action describing whether prefix/suffix was UPDATED or DELETED.
318 public static function updateRecords(&$optionValueId, $action) {
320 $optionValue = new CRM_Core_DAO_OptionValue();
321 $optionValue->id
= $optionValueId;
322 $optionValue->find(TRUE);
324 $optionGroup = new CRM_Core_DAO_OptionGroup();
325 $optionGroup->id
= $optionValue->option_group_id
;
326 $optionGroup->find(TRUE);
329 $gName = $optionGroup->name
;
331 $value = $optionValue->value
;
333 // get the proper group name & affected field name
334 // todo: this may no longer be needed for individuals - check inputs
335 $individuals = array(
336 'gender' => 'gender_id',
337 'individual_prefix' => 'prefix_id',
338 'individual_suffix' => 'suffix_id',
339 'communication_style' => 'communication_style_id',
340 // Not only Individuals -- but the code seems to be generic for all contact types, despite the naming...
342 $contributions = array('payment_instrument' => 'payment_instrument_id');
343 $activities = array('activity_type' => 'activity_type_id');
344 $participant = array('participant_role' => 'role_id');
345 $eventType = array('event_type' => 'event_type_id');
346 $aclRole = array('acl_role' => 'acl_role_id');
348 $all = array_merge($individuals, $contributions, $activities, $participant, $eventType, $aclRole);
351 foreach ($all as $name => $id) {
352 if ($gName == $name) {
356 if ($fieldName == '') {
360 if (array_key_exists($gName, $individuals)) {
361 $contactDAO = new CRM_Contact_DAO_Contact();
363 $contactDAO->$fieldName = $value;
366 while ($contactDAO->fetch()) {
367 if ($action == CRM_Core_Action
::DELETE
) {
368 $contact = new CRM_Contact_DAO_Contact();
369 $contact->id
= $contactDAO->id
;
370 $contact->find(TRUE);
372 // make sure dates doesn't get reset
373 $contact->birth_date
= CRM_Utils_Date
::isoToMysql($contact->birth_date
);
374 $contact->deceased_date
= CRM_Utils_Date
::isoToMysql($contact->deceased_date
);
375 $contact->$fieldName = 'NULL';
383 if (array_key_exists($gName, $contributions)) {
384 $contribution = new CRM_Contribute_DAO_Contribution();
385 $contribution->$fieldName = $value;
386 $contribution->find();
387 while ($contribution->fetch()) {
388 if ($action == CRM_Core_Action
::DELETE
) {
389 $contribution->$fieldName = 'NULL';
390 $contribution->save();
396 if (array_key_exists($gName, $activities)) {
397 $activity = new CRM_Activity_DAO_Activity();
398 $activity->$fieldName = $value;
400 while ($activity->fetch()) {
406 //delete participant role, type and event type option value
407 if (array_key_exists($gName, $participant)) {
408 $participantValue = new CRM_Event_DAO_Participant();
409 $participantValue->$fieldName = $value;
410 if ($participantValue->find(TRUE)) {
416 //delete event type option value
417 if (array_key_exists($gName, $eventType)) {
418 $event = new CRM_Event_DAO_Event();
419 $event->$fieldName = $value;
420 if ($event->find(TRUE)) {
426 //delete acl_role option value
427 if (array_key_exists($gName, $aclRole)) {
428 $entityRole = new CRM_ACL_DAO_EntityRole();
429 $entityRole->$fieldName = $value;
431 $aclDAO = new CRM_ACL_DAO_ACL();
432 $aclDAO->entity_id
= $value;
433 if ($entityRole->find(TRUE) ||
$aclDAO->find(TRUE)) {
441 * Updates options values weights.
443 * @param int $opGroupId
444 * @param array $opWeights
445 * Options value , weight pair.
447 public static function updateOptionWeights($opGroupId, $opWeights) {
448 if (!is_array($opWeights) ||
empty($opWeights)) {
452 foreach ($opWeights as $opValue => $opWeight) {
453 $optionValue = new CRM_Core_DAO_OptionValue();
454 $optionValue->option_group_id
= $opGroupId;
455 $optionValue->value
= $opValue;
456 if ($optionValue->find(TRUE)) {
457 $optionValue->weight
= $opWeight;
458 $optionValue->save();
460 $optionValue->free();
465 * Get the values of all option values given an option group ID. Store in system cache
466 * Does not take any filtering arguments. The object is to avoid hitting the DB and retrieve
469 * @param int $optionGroupID
470 * The option group for which we want the values from.
473 * an array of array of values for this option group
475 public static function getOptionValuesArray($optionGroupID) {
476 // check if we can get the field values from the system cache
477 $cacheKey = "CRM_Core_BAO_OptionValue_OptionGroupID_{$optionGroupID}";
478 $cache = CRM_Utils_Cache
::singleton();
479 $optionValues = $cache->get($cacheKey);
480 if (empty($optionValues)) {
481 $dao = new CRM_Core_DAO_OptionValue();
482 $dao->option_group_id
= $optionGroupID;
483 $dao->orderBy('weight ASC, label ASC');
486 $optionValues = array();
487 while ($dao->fetch()) {
488 $optionValues[$dao->id
] = array();
489 CRM_Core_DAO
::storeValues($dao, $optionValues[$dao->id
]);
492 $cache->set($cacheKey, $optionValues);
495 return $optionValues;
499 * Get the values of all option values given an option group ID as a key => value pair
500 * Use above cached function to make it super efficient
502 * @param int $optionGroupID
503 * The option group for which we want the values from.
506 * an associative array of label, value pairs
508 public static function getOptionValuesAssocArray($optionGroupID) {
509 $optionValues = self
::getOptionValuesArray($optionGroupID);
512 foreach ($optionValues as $id => $value) {
513 $options[$value['value']] = $value['label'];
519 * Get the values of all option values given an option group Name as a key => value pair
520 * Use above cached function to make it super efficient
522 * @param string $optionGroupName
523 * The option group name for which we want the values from.
526 * an associative array of label, value pairs
528 public static function getOptionValuesAssocArrayFromName($optionGroupName) {
529 $dao = new CRM_Core_DAO_OptionGroup();
530 $dao->name
= $optionGroupName;
532 $dao->selectAdd('id');
534 $optionValues = self
::getOptionValuesArray($dao->id
);
537 foreach ($optionValues as $id => $value) {
538 $options[$value['value']] = $value['label'];
544 * Ensure an option value exists.
546 * This function is intended to be called from the upgrade script to ensure
547 * that an option value exists, without hitting an error if it already exists.
549 * This is sympathetic to sites who might pre-add it.
551 * @param array $params the option value attributes.
552 * @return array the option value attributes.
554 public static function ensureOptionValueExists($params) {
555 $result = civicrm_api3('OptionValue', 'get', array(
556 'option_group_id' => $params['option_group_id'],
557 'name' => $params['name'],
558 'return' => ['id', 'value'],
562 if (!$result['count']) {
563 $result = civicrm_api3('OptionValue', 'create', $params);
566 return CRM_Utils_Array
::first($result['values']);