Merge pull request #21965 from civicrm/5.43
[civicrm-core.git] / CRM / Core / BAO / OptionValue.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17class CRM_Core_BAO_OptionValue extends CRM_Core_DAO_OptionValue {
18
19 /**
fe482240 20 * Class constructor.
6a488035 21 */
00be9182 22 public function __construct() {
6a488035
TO
23 parent::__construct();
24 }
77b97be7 25
9fe6051a 26 /**
8eedd10a 27 * Create option value.
28 *
29 * Note that the create function calls 'add' but has more business logic.
77b97be7 30 *
6a0b768e
TO
31 * @param array $params
32 * Input parameters.
77b97be7 33 *
d8efe404 34 * @return CRM_Core_DAO_OptionValue
35 * @throws \CRM_Core_Exception
77b97be7 36 */
00be9182 37 public static function create($params) {
9b873358 38 if (empty($params['id'])) {
c87bbced 39 self::setDefaults($params);
40 }
d8efe404 41 return CRM_Core_BAO_OptionValue::add($params);
c87bbced 42 }
353ffa53 43
c87bbced 44 /**
fe482240 45 * Set default Parameters.
c87bbced 46 * This functions sets default parameters if not set:
47 * - name & label are set to each other as required (it might make more sense for one
48 * to be required but this would mean a change to the api level)
9fe6051a 49 * - weight & value will be set to their respective option groups next values
50 * if nothing is passed in.
51 *
52 * Note this function does not check for presence of $params['id'] so should only be called
53 * if 'id' is not present
c87bbced 54 *
9fe6051a 55 * @param array $params
c87bbced 56 */
9b873358 57 public static function setDefaults(&$params) {
a8504da4
CW
58 $params['label'] = $params['label'] ?? $params['name'];
59 $params['name'] = $params['name'] ?? CRM_Utils_String::titleToVar($params['label']);
60 $params['weight'] = $params['weight'] ?? self::getDefaultWeight($params);
61 $params['value'] = $params['value'] ?? self::getDefaultValue($params);
c87bbced 62 }
77b97be7 63
9fe6051a 64 /**
fe482240 65 * Get next available value.
9fe6051a 66 * We will take the highest numeric value (or 0 if no numeric values exist)
67 * and add one. The calling function is responsible for any
68 * more complex decision making
77b97be7 69 *
9fe6051a 70 * @param array $params
77b97be7
EM
71 *
72 * @return int
9fe6051a 73 */
9b873358 74 public static function getDefaultWeight($params) {
1c6b7d30 75 return (int) CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue',
be2fb01f 76 ['option_group_id' => $params['option_group_id']]);
1c6b7d30 77 }
78
79 /**
0880a9d0 80 * Get next available value.
1c6b7d30 81 * We will take the highest numeric value (or 0 if no numeric values exist)
82 * and add one. The calling function is responsible for any
83 * more complex decision making
84 * @param array $params
85 */
9b873358 86 public static function getDefaultValue($params) {
353ffa53
TO
87 $bao = new CRM_Core_BAO_OptionValue();
88 $bao->option_group_id = $params['option_group_id'];
89 if (isset($params['domain_id'])) {
90 $bao->domain_id = $params['domain_id'];
91 }
92 $bao->selectAdd();
93 $bao->whereAdd("value REGEXP '^[0-9]+$'");
94 $bao->selectAdd('(ROUND(COALESCE(MAX(CONVERT(value, UNSIGNED)),0)) +1) as nextvalue');
95 $bao->find(TRUE);
96 return $bao->nextvalue;
9fe6051a 97 }
353ffa53 98
6a488035 99 /**
fe482240 100 * Fetch object based on array of properties.
6a488035 101 *
6a0b768e
TO
102 * @param array $params
103 * (reference ) an assoc array of name/value pairs.
104 * @param array $defaults
105 * (reference ) an assoc array to hold the flattened values.
6a488035 106 *
16b10e64 107 * @return CRM_Core_BAO_OptionValue
6a488035 108 */
00be9182 109 public static function retrieve(&$params, &$defaults) {
6a488035
TO
110 $optionValue = new CRM_Core_DAO_OptionValue();
111 $optionValue->copyValues($params);
112 if ($optionValue->find(TRUE)) {
113 CRM_Core_DAO::storeValues($optionValue, $defaults);
114 return $optionValue;
115 }
116 return NULL;
117 }
118
119 /**
fe482240 120 * Update the is_active flag in the db.
6a488035 121 *
6a0b768e
TO
122 * @param int $id
123 * Id of the database record.
124 * @param bool $is_active
125 * Value we want to set the is_active field.
6a488035 126 *
8a4fede3 127 * @return bool
128 * true if we found and updated the object, else false
6a488035 129 */
00be9182 130 public static function setIsActive($id, $is_active) {
6a488035
TO
131 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_OptionValue', $id, 'is_active', $is_active);
132 }
133
134 /**
fe482240 135 * Add an Option Value.
6a488035 136 *
6a0b768e
TO
137 * @param array $params
138 * Reference array contains the values submitted by the form.
139 * @param array $ids
d0488daf 140 * deprecated Reference array contains the id.
6a488035 141 *
d0488daf 142 * @return \CRM_Core_DAO_OptionValue
d8efe404 143 *
d0488daf 144 * @throws \CRM_Core_Exception
d8efe404 145 * @throws \CiviCRM_API3_Exception
6a488035 146 */
be2fb01f 147 public static function add(&$params, $ids = []) {
d8efe404 148 if (!empty($ids['optionValue']) && empty($params['id'])) {
149 CRM_Core_Error::deprecatedFunctionWarning('$params[\'id\'] should be set, $ids is deprecated');
150 }
8df1a020 151 $id = $params['id'] ?? $ids['optionValue'] ?? NULL;
0298dd55 152
58eaa092 153 // Update custom field data to reflect the new value
0298dd55 154 if ($id && isset($params['value'])) {
d0488daf 155 CRM_Core_BAO_CustomOption::updateValue($id, $params['value']);
58eaa092 156 }
6a488035 157
d0488daf 158 // We need to have option_group_id populated for validation so load if necessary.
159 if (empty($params['option_group_id'])) {
160 $params['option_group_id'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue',
161 $id, 'option_group_id', 'id'
162 );
163 }
164 $groupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup',
165 $params['option_group_id'], 'name', 'id'
166 );
167
6a488035
TO
168 // action is taken depending upon the mode
169 $optionValue = new CRM_Core_DAO_OptionValue();
170 $optionValue->copyValues($params);
171
80d323a0
CW
172 $isDomainOptionGroup = in_array($groupName, CRM_Core_OptionGroup::$_domainIDGroups);
173 if (empty($params['domain_id']) && $isDomainOptionGroup) {
174 $optionValue->domain_id = CRM_Core_Config::domainID();
175 }
176
177 // When setting a default option, unset other options in this group as default
a7488080 178 if (!empty($params['is_default'])) {
6a488035
TO
179 $query = 'UPDATE civicrm_option_value SET is_default = 0 WHERE option_group_id = %1';
180
181 // tweak default reset, and allow multiple default within group.
182 if ($resetDefaultFor = CRM_Utils_Array::value('reset_default_for', $params)) {
183 if (is_array($resetDefaultFor)) {
184 $colName = key($resetDefaultFor);
185 $colVal = $resetDefaultFor[$colName];
186 $query .= " AND ( $colName IN ( $colVal ) )";
187 }
188 }
189
be2fb01f 190 $p = [1 => [$params['option_group_id'], 'Integer']];
89ab5601 191
80d323a0
CW
192 // Limit update by domain of option
193 $domain = $optionValue->domain_id ?? NULL;
194 if (!$domain && $id && $isDomainOptionGroup) {
195 $domain = CRM_Core_DAO::getFieldValue(__CLASS__, $id, 'domain_id');
196 }
197 if ($domain) {
198 $query .= ' AND domain_id = %2';
199 $p[2] = [$domain, 'Integer'];
200 }
201
202 CRM_Core_DAO::executeQuery($query, $p);
89ab5601
PJ
203 }
204
d0488daf 205 $groupsSupportingDuplicateValues = ['languages'];
206 if (!$id && !empty($params['value'])) {
e5720c45 207 $dao = new CRM_Core_DAO_OptionValue();
d0488daf 208 if (!in_array($groupName, $groupsSupportingDuplicateValues)) {
209 $dao->value = $params['value'];
210 }
211 else {
212 // CRM-21737 languages option group does not use unique values but unique names.
213 $dao->name = $params['name'];
214 }
215 if (in_array($groupName, CRM_Core_OptionGroup::$_domainIDGroups)) {
216 $dao->domain_id = $optionValue->domain_id;
217 }
218 $dao->option_group_id = $params['option_group_id'];
e5720c45
SL
219 if ($dao->find(TRUE)) {
220 throw new CRM_Core_Exception('Value already exists in the database');
221 }
222 }
6a488035 223
d0488daf 224 $optionValue->id = $id;
6a488035 225 $optionValue->save();
a4a33486 226 CRM_Core_PseudoConstant::flush();
a900072c 227
49bade89 228 // Create relationship for payment instrument options
a900072c
PN
229 if (!empty($params['financial_account_id'])) {
230 $optionName = civicrm_api3('OptionGroup', 'getvalue', [
231 'return' => 'name',
232 'id' => $params['option_group_id'],
233 ]);
49bade89 234 // Only create relationship for payment instrument options
a900072c
PN
235 if ($optionName == 'payment_instrument') {
236 $relationTypeId = civicrm_api3('OptionValue', 'getvalue', [
237 'return' => 'value',
238 'option_group_id' => 'account_relationship',
239 'name' => 'Asset Account is',
240 ]);
241 $params = [
242 'entity_table' => 'civicrm_option_value',
243 'entity_id' => $optionValue->id,
244 'account_relationship' => $relationTypeId,
245 'financial_account_id' => $params['financial_account_id'],
246 ];
247 CRM_Financial_BAO_FinancialTypeAccount::add($params);
248 }
249 }
6a488035
TO
250 return $optionValue;
251 }
252
253 /**
fe482240 254 * Delete Option Value.
6a488035 255 *
c490a46a 256 * @param int $optionValueId
6a488035 257 *
5c766a0b 258 * @return bool
6a488035 259 *
6a488035 260 */
00be9182 261 public static function del($optionValueId) {
6a488035
TO
262 $optionValue = new CRM_Core_DAO_OptionValue();
263 $optionValue->id = $optionValueId;
a60c0bc8
SL
264 if (!$optionValue->find()) {
265 return FALSE;
266 }
6a488035 267 if (self::updateRecords($optionValueId, CRM_Core_Action::DELETE)) {
a4a33486 268 CRM_Core_PseudoConstant::flush();
a60c0bc8
SL
269 $optionValue->delete();
270 return TRUE;
6a488035
TO
271 }
272 return FALSE;
273 }
274
275 /**
fe482240 276 * Retrieve activity type label and description.
6a488035 277 *
6a0b768e
TO
278 * @param int $activityTypeId
279 * Activity type id.
6a488035 280 *
a6c01b45
CW
281 * @return array
282 * label and description
6a488035 283 */
00be9182 284 public static function getActivityTypeDetails($activityTypeId) {
6a488035
TO
285 $query = "SELECT civicrm_option_value.label, civicrm_option_value.description
286 FROM civicrm_option_value
287 LEFT JOIN civicrm_option_group ON ( civicrm_option_value.option_group_id = civicrm_option_group.id )
288 WHERE civicrm_option_group.name = 'activity_type'
289 AND civicrm_option_value.value = {$activityTypeId} ";
290
291 $dao = CRM_Core_DAO::executeQuery($query);
292
293 $dao->fetch();
294
be2fb01f 295 return [$dao->label, $dao->description];
6a488035
TO
296 }
297
298 /**
299 * Get the Option Value title.
300 *
6a0b768e
TO
301 * @param int $id
302 * Id of Option Value.
6a488035 303 *
a6c01b45
CW
304 * @return string
305 * title
6a488035 306 *
6a488035
TO
307 */
308 public static function getTitle($id) {
309 return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $id, 'label');
310 }
311
312 /**
100fef9d 313 * Updates contacts affected by the option value passed.
6a488035 314 *
6a0b768e
TO
315 * @param int $optionValueId
316 * The option value id.
317 * @param int $action
318 * The action describing whether prefix/suffix was UPDATED or DELETED.
6a488035 319 *
7a6073fd 320 * @return bool
6a488035 321 */
00be9182 322 public static function updateRecords(&$optionValueId, $action) {
6a488035
TO
323 //finding group name
324 $optionValue = new CRM_Core_DAO_OptionValue();
325 $optionValue->id = $optionValueId;
326 $optionValue->find(TRUE);
327
328 $optionGroup = new CRM_Core_DAO_OptionGroup();
329 $optionGroup->id = $optionValue->option_group_id;
330 $optionGroup->find(TRUE);
331
332 // group name
333 $gName = $optionGroup->name;
334 // value
335 $value = $optionValue->value;
336
337 // get the proper group name & affected field name
67744c4e 338 // todo: this may no longer be needed for individuals - check inputs
be2fb01f 339 $individuals = [
6a488035
TO
340 'gender' => 'gender_id',
341 'individual_prefix' => 'prefix_id',
342 'individual_suffix' => 'suffix_id',
353ffa53
TO
343 'communication_style' => 'communication_style_id',
344 // Not only Individuals -- but the code seems to be generic for all contact types, despite the naming...
be2fb01f
CW
345 ];
346 $contributions = ['payment_instrument' => 'payment_instrument_id'];
347 $activities = ['activity_type' => 'activity_type_id'];
348 $participant = ['participant_role' => 'role_id'];
349 $eventType = ['event_type' => 'event_type_id'];
350 $aclRole = ['acl_role' => 'acl_role_id'];
6a488035
TO
351
352 $all = array_merge($individuals, $contributions, $activities, $participant, $eventType, $aclRole);
353 $fieldName = '';
354
355 foreach ($all as $name => $id) {
356 if ($gName == $name) {
357 $fieldName = $id;
358 }
359 }
360 if ($fieldName == '') {
361 return TRUE;
362 }
363
364 if (array_key_exists($gName, $individuals)) {
365 $contactDAO = new CRM_Contact_DAO_Contact();
366
367 $contactDAO->$fieldName = $value;
368 $contactDAO->find();
369
370 while ($contactDAO->fetch()) {
371 if ($action == CRM_Core_Action::DELETE) {
372 $contact = new CRM_Contact_DAO_Contact();
373 $contact->id = $contactDAO->id;
374 $contact->find(TRUE);
375
376 // make sure dates doesn't get reset
377 $contact->birth_date = CRM_Utils_Date::isoToMysql($contact->birth_date);
378 $contact->deceased_date = CRM_Utils_Date::isoToMysql($contact->deceased_date);
379 $contact->$fieldName = 'NULL';
380 $contact->save();
381 }
382 }
383
384 return TRUE;
385 }
386
387 if (array_key_exists($gName, $contributions)) {
388 $contribution = new CRM_Contribute_DAO_Contribution();
389 $contribution->$fieldName = $value;
390 $contribution->find();
391 while ($contribution->fetch()) {
392 if ($action == CRM_Core_Action::DELETE) {
393 $contribution->$fieldName = 'NULL';
394 $contribution->save();
395 }
396 }
397 return TRUE;
398 }
399
400 if (array_key_exists($gName, $activities)) {
401 $activity = new CRM_Activity_DAO_Activity();
402 $activity->$fieldName = $value;
403 $activity->find();
404 while ($activity->fetch()) {
405 $activity->delete();
406 }
407 return TRUE;
408 }
409
410 //delete participant role, type and event type option value
411 if (array_key_exists($gName, $participant)) {
412 $participantValue = new CRM_Event_DAO_Participant();
413 $participantValue->$fieldName = $value;
414 if ($participantValue->find(TRUE)) {
415 return FALSE;
416 }
417 return TRUE;
418 }
419
420 //delete event type option value
421 if (array_key_exists($gName, $eventType)) {
422 $event = new CRM_Event_DAO_Event();
423 $event->$fieldName = $value;
424 if ($event->find(TRUE)) {
425 return FALSE;
426 }
427 return TRUE;
428 }
429
430 //delete acl_role option value
431 if (array_key_exists($gName, $aclRole)) {
432 $entityRole = new CRM_ACL_DAO_EntityRole();
433 $entityRole->$fieldName = $value;
434
435 $aclDAO = new CRM_ACL_DAO_ACL();
436 $aclDAO->entity_id = $value;
437 if ($entityRole->find(TRUE) || $aclDAO->find(TRUE)) {
438 return FALSE;
439 }
440 return TRUE;
441 }
442 }
443
444 /**
100fef9d 445 * Updates options values weights.
6a488035 446 *
c490a46a 447 * @param int $opGroupId
6a0b768e
TO
448 * @param array $opWeights
449 * Options value , weight pair.
6a488035 450 */
00be9182 451 public static function updateOptionWeights($opGroupId, $opWeights) {
6a488035
TO
452 if (!is_array($opWeights) || empty($opWeights)) {
453 return;
454 }
455
456 foreach ($opWeights as $opValue => $opWeight) {
457 $optionValue = new CRM_Core_DAO_OptionValue();
458 $optionValue->option_group_id = $opGroupId;
459 $optionValue->value = $opValue;
460 if ($optionValue->find(TRUE)) {
461 $optionValue->weight = $opWeight;
462 $optionValue->save();
463 }
6a488035
TO
464 }
465 }
466
467 /**
468 * Get the values of all option values given an option group ID. Store in system cache
469 * Does not take any filtering arguments. The object is to avoid hitting the DB and retrieve
470 * from memory
471 *
6a0b768e
TO
472 * @param int $optionGroupID
473 * The option group for which we want the values from.
6a488035 474 *
a6c01b45
CW
475 * @return array
476 * an array of array of values for this option group
6a488035 477 */
00be9182 478 public static function getOptionValuesArray($optionGroupID) {
6a488035 479 // check if we can get the field values from the system cache
353ffa53
TO
480 $cacheKey = "CRM_Core_BAO_OptionValue_OptionGroupID_{$optionGroupID}";
481 $cache = CRM_Utils_Cache::singleton();
6a488035
TO
482 $optionValues = $cache->get($cacheKey);
483 if (empty($optionValues)) {
484 $dao = new CRM_Core_DAO_OptionValue();
485 $dao->option_group_id = $optionGroupID;
486 $dao->orderBy('weight ASC, label ASC');
487 $dao->find();
488
be2fb01f 489 $optionValues = [];
6a488035 490 while ($dao->fetch()) {
be2fb01f 491 $optionValues[$dao->id] = [];
6a488035
TO
492 CRM_Core_DAO::storeValues($dao, $optionValues[$dao->id]);
493 }
494
495 $cache->set($cacheKey, $optionValues);
496 }
497
498 return $optionValues;
499 }
500
501 /**
502 * Get the values of all option values given an option group ID as a key => value pair
503 * Use above cached function to make it super efficient
504 *
6a0b768e
TO
505 * @param int $optionGroupID
506 * The option group for which we want the values from.
6a488035 507 *
a6c01b45
CW
508 * @return array
509 * an associative array of label, value pairs
6a488035 510 */
00be9182 511 public static function getOptionValuesAssocArray($optionGroupID) {
6a488035
TO
512 $optionValues = self::getOptionValuesArray($optionGroupID);
513
be2fb01f 514 $options = [];
6a488035
TO
515 foreach ($optionValues as $id => $value) {
516 $options[$value['value']] = $value['label'];
517 }
518 return $options;
519 }
353ffa53 520
6a488035
TO
521 /**
522 * Get the values of all option values given an option group Name as a key => value pair
523 * Use above cached function to make it super efficient
524 *
6a0b768e
TO
525 * @param string $optionGroupName
526 * The option group name for which we want the values from.
6a488035 527 *
a6c01b45
CW
528 * @return array
529 * an associative array of label, value pairs
6a488035 530 */
00be9182 531 public static function getOptionValuesAssocArrayFromName($optionGroupName) {
6a488035
TO
532 $dao = new CRM_Core_DAO_OptionGroup();
533 $dao->name = $optionGroupName;
534 $dao->selectAdd();
535 $dao->selectAdd('id');
536 $dao->find(TRUE);
537 $optionValues = self::getOptionValuesArray($dao->id);
538
be2fb01f 539 $options = [];
6a488035
TO
540 foreach ($optionValues as $id => $value) {
541 $options[$value['value']] = $value['label'];
542 }
543 return $options;
544 }
545
6f408d71 546 /**
547 * Ensure an option value exists.
548 *
549 * This function is intended to be called from the upgrade script to ensure
550 * that an option value exists, without hitting an error if it already exists.
551 *
552 * This is sympathetic to sites who might pre-add it.
ad8d1ce3
RO
553 *
554 * @param array $params the option value attributes.
555 * @return array the option value attributes.
6f408d71 556 */
557 public static function ensureOptionValueExists($params) {
be2fb01f 558 $result = civicrm_api3('OptionValue', 'get', [
bf87703e 559 'option_group_id' => $params['option_group_id'],
6f408d71 560 'name' => $params['name'],
ad8d1ce3
RO
561 'return' => ['id', 'value'],
562 'sequential' => 1,
be2fb01f 563 ]);
ad8d1ce3
RO
564
565 if (!$result['count']) {
566 $result = civicrm_api3('OptionValue', 'create', $params);
6f408d71 567 }
ad8d1ce3
RO
568
569 return CRM_Utils_Array::first($result['values']);
6f408d71 570 }
571
6a488035 572}