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