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