Merge pull request #23211 from eileenmcnaughton/event1
[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 * Retrieve DB object and copy to defaults array.
94 *
95 * @param array $params
96 * Array of criteria values.
97 * @param array $defaults
98 * Array to be populated with found values.
99 *
100 * @return self|null
101 * The DAO object, if found.
102 *
103 * @deprecated
104 */
105 public static function retrieve($params, &$defaults) {
106 return self::commonRetrieve(self::class, $params, $defaults);
107 }
108
109 /**
110 * Update the is_active flag in the db.
111 *
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.
116 *
117 * @return bool
118 * true if we found and updated the object, else false
119 */
120 public static function setIsActive($id, $is_active) {
121 return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_OptionValue', $id, 'is_active', $is_active);
122 }
123
124 /**
125 * Add an Option Value.
126 *
127 * @param array $params
128 * Reference array contains the values submitted by the form.
129 * @param array $ids
130 * deprecated Reference array contains the id.
131 *
132 * @return \CRM_Core_DAO_OptionValue
133 *
134 * @throws \CRM_Core_Exception
135 * @throws \CiviCRM_API3_Exception
136 */
137 public static function add(&$params, $ids = []) {
138 if (!empty($ids['optionValue']) && empty($params['id'])) {
139 CRM_Core_Error::deprecatedFunctionWarning('$params[\'id\'] should be set, $ids is deprecated');
140 }
141 $id = $params['id'] ?? $ids['optionValue'] ?? NULL;
142
143 // Update custom field data to reflect the new value
144 if ($id && isset($params['value'])) {
145 CRM_Core_BAO_CustomOption::updateValue($id, $params['value']);
146 }
147
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
158 $op = $id ? 'edit' : 'create';
159 CRM_Utils_Hook::pre($op, 'OptionValue', $id, $params);
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 CRM_Utils_Hook::post($op, 'OptionValue', $id, $optionValue);
225
226 // Create relationship for payment instrument options
227 if (!empty($params['financial_account_id'])) {
228 $optionName = civicrm_api3('OptionGroup', 'getvalue', [
229 'return' => 'name',
230 'id' => $params['option_group_id'],
231 ]);
232 // Only create relationship for payment instrument options
233 if ($optionName == 'payment_instrument') {
234 $relationTypeId = civicrm_api3('OptionValue', 'getvalue', [
235 'return' => 'value',
236 'option_group_id' => 'account_relationship',
237 'name' => 'Asset Account is',
238 ]);
239 $params = [
240 'entity_table' => 'civicrm_option_value',
241 'entity_id' => $optionValue->id,
242 'account_relationship' => $relationTypeId,
243 'financial_account_id' => $params['financial_account_id'],
244 ];
245 CRM_Financial_BAO_FinancialTypeAccount::add($params);
246 }
247 }
248 return $optionValue;
249 }
250
251 /**
252 * Delete Option Value.
253 *
254 * @param int $optionValueId
255 *
256 * @return bool
257 *
258 */
259 public static function del($optionValueId) {
260 $optionValue = new CRM_Core_DAO_OptionValue();
261 $optionValue->id = $optionValueId;
262 if (!$optionValue->find()) {
263 return FALSE;
264 }
265 $hookParams = ['id' => $optionValueId];
266 CRM_Utils_Hook::pre('delete', 'OptionValue', $optionValueId, $hookParams);
267 if (self::updateRecords($optionValueId, CRM_Core_Action::DELETE)) {
268 CRM_Core_PseudoConstant::flush();
269 $optionValue->delete();
270 CRM_Utils_Hook::post('delete', 'OptionValue', $optionValueId, $optionValue);
271 return TRUE;
272 }
273 return FALSE;
274 }
275
276 /**
277 * Retrieve activity type label and description.
278 *
279 * @param int $activityTypeId
280 * Activity type id.
281 *
282 * @return array
283 * label and description
284 */
285 public static function getActivityTypeDetails($activityTypeId) {
286 $query = "SELECT civicrm_option_value.label, civicrm_option_value.description
287 FROM civicrm_option_value
288 LEFT JOIN civicrm_option_group ON ( civicrm_option_value.option_group_id = civicrm_option_group.id )
289 WHERE civicrm_option_group.name = 'activity_type'
290 AND civicrm_option_value.value = {$activityTypeId} ";
291
292 $dao = CRM_Core_DAO::executeQuery($query);
293
294 $dao->fetch();
295
296 return [$dao->label, $dao->description];
297 }
298
299 /**
300 * Get the Option Value title.
301 *
302 * @param int $id
303 * Id of Option Value.
304 *
305 * @return string
306 * title
307 *
308 */
309 public static function getTitle($id) {
310 return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $id, 'label');
311 }
312
313 /**
314 * Updates contacts affected by the option value passed.
315 *
316 * @param int $optionValueId
317 * The option value id.
318 * @param int $action
319 * The action describing whether prefix/suffix was UPDATED or DELETED.
320 *
321 * @return bool
322 */
323 public static function updateRecords(&$optionValueId, $action) {
324 //finding group name
325 $optionValue = new CRM_Core_DAO_OptionValue();
326 $optionValue->id = $optionValueId;
327 $optionValue->find(TRUE);
328
329 $optionGroup = new CRM_Core_DAO_OptionGroup();
330 $optionGroup->id = $optionValue->option_group_id;
331 $optionGroup->find(TRUE);
332
333 // group name
334 $gName = $optionGroup->name;
335 // value
336 $value = $optionValue->value;
337
338 // get the proper group name & affected field name
339 // todo: this may no longer be needed for individuals - check inputs
340 $individuals = [
341 'gender' => 'gender_id',
342 'individual_prefix' => 'prefix_id',
343 'individual_suffix' => 'suffix_id',
344 'communication_style' => 'communication_style_id',
345 // Not only Individuals -- but the code seems to be generic for all contact types, despite the naming...
346 ];
347 $contributions = ['payment_instrument' => 'payment_instrument_id'];
348 $activities = ['activity_type' => 'activity_type_id'];
349 $participant = ['participant_role' => 'role_id'];
350 $eventType = ['event_type' => 'event_type_id'];
351 $aclRole = ['acl_role' => 'acl_role_id'];
352
353 $all = array_merge($individuals, $contributions, $activities, $participant, $eventType, $aclRole);
354 $fieldName = '';
355
356 foreach ($all as $name => $id) {
357 if ($gName == $name) {
358 $fieldName = $id;
359 }
360 }
361 if ($fieldName == '') {
362 return TRUE;
363 }
364
365 if (array_key_exists($gName, $individuals)) {
366 $contactDAO = new CRM_Contact_DAO_Contact();
367
368 $contactDAO->$fieldName = $value;
369 $contactDAO->find();
370
371 while ($contactDAO->fetch()) {
372 if ($action == CRM_Core_Action::DELETE) {
373 $contact = new CRM_Contact_DAO_Contact();
374 $contact->id = $contactDAO->id;
375 $contact->find(TRUE);
376
377 // make sure dates doesn't get reset
378 $contact->birth_date = CRM_Utils_Date::isoToMysql($contact->birth_date);
379 $contact->deceased_date = CRM_Utils_Date::isoToMysql($contact->deceased_date);
380 $contact->$fieldName = 'NULL';
381 $contact->save();
382 }
383 }
384
385 return TRUE;
386 }
387
388 if (array_key_exists($gName, $contributions)) {
389 $contribution = new CRM_Contribute_DAO_Contribution();
390 $contribution->$fieldName = $value;
391 $contribution->find();
392 while ($contribution->fetch()) {
393 if ($action == CRM_Core_Action::DELETE) {
394 $contribution->$fieldName = 'NULL';
395 $contribution->save();
396 }
397 }
398 return TRUE;
399 }
400
401 if (array_key_exists($gName, $activities)) {
402 $activity = new CRM_Activity_DAO_Activity();
403 $activity->$fieldName = $value;
404 $activity->find();
405 while ($activity->fetch()) {
406 $activity->delete();
407 }
408 return TRUE;
409 }
410
411 //delete participant role, type and event type option value
412 if (array_key_exists($gName, $participant)) {
413 $participantValue = new CRM_Event_DAO_Participant();
414 $participantValue->$fieldName = $value;
415 if ($participantValue->find(TRUE)) {
416 return FALSE;
417 }
418 return TRUE;
419 }
420
421 //delete event type option value
422 if (array_key_exists($gName, $eventType)) {
423 $event = new CRM_Event_DAO_Event();
424 $event->$fieldName = $value;
425 if ($event->find(TRUE)) {
426 return FALSE;
427 }
428 return TRUE;
429 }
430
431 //delete acl_role option value
432 if (array_key_exists($gName, $aclRole)) {
433 $entityRole = new CRM_ACL_DAO_EntityRole();
434 $entityRole->$fieldName = $value;
435
436 $aclDAO = new CRM_ACL_DAO_ACL();
437 $aclDAO->entity_id = $value;
438 if ($entityRole->find(TRUE) || $aclDAO->find(TRUE)) {
439 return FALSE;
440 }
441 return TRUE;
442 }
443 }
444
445 /**
446 * Updates options values weights.
447 *
448 * @param int $opGroupId
449 * @param array $opWeights
450 * Options value , weight pair.
451 */
452 public static function updateOptionWeights($opGroupId, $opWeights) {
453 if (!is_array($opWeights) || empty($opWeights)) {
454 return;
455 }
456
457 foreach ($opWeights as $opValue => $opWeight) {
458 $optionValue = new CRM_Core_DAO_OptionValue();
459 $optionValue->option_group_id = $opGroupId;
460 $optionValue->value = $opValue;
461 if ($optionValue->find(TRUE)) {
462 $optionValue->weight = $opWeight;
463 $optionValue->save();
464 }
465 }
466 }
467
468 /**
469 * Get the values of all option values given an option group ID. Store in system cache
470 * Does not take any filtering arguments. The object is to avoid hitting the DB and retrieve
471 * from memory
472 *
473 * @param int $optionGroupID
474 * The option group for which we want the values from.
475 *
476 * @return array
477 * an array of array of values for this option group
478 */
479 public static function getOptionValuesArray($optionGroupID) {
480 // check if we can get the field values from the system cache
481 $cacheKey = "CRM_Core_BAO_OptionValue_OptionGroupID_{$optionGroupID}";
482 $cache = CRM_Utils_Cache::singleton();
483 $optionValues = $cache->get($cacheKey);
484 if (empty($optionValues)) {
485 $dao = new CRM_Core_DAO_OptionValue();
486 $dao->option_group_id = $optionGroupID;
487 $dao->orderBy('weight ASC, label ASC');
488 $dao->find();
489
490 $optionValues = [];
491 while ($dao->fetch()) {
492 $optionValues[$dao->id] = [];
493 CRM_Core_DAO::storeValues($dao, $optionValues[$dao->id]);
494 }
495
496 $cache->set($cacheKey, $optionValues);
497 }
498
499 return $optionValues;
500 }
501
502 /**
503 * Get the values of all option values given an option group ID as a key => value pair
504 * Use above cached function to make it super efficient
505 *
506 * @param int $optionGroupID
507 * The option group for which we want the values from.
508 *
509 * @return array
510 * an associative array of label, value pairs
511 */
512 public static function getOptionValuesAssocArray($optionGroupID) {
513 $optionValues = self::getOptionValuesArray($optionGroupID);
514
515 $options = [];
516 foreach ($optionValues as $id => $value) {
517 $options[$value['value']] = $value['label'];
518 }
519 return $options;
520 }
521
522 /**
523 * Get the values of all option values given an option group Name as a key => value pair
524 * Use above cached function to make it super efficient
525 *
526 * @param string $optionGroupName
527 * The option group name for which we want the values from.
528 *
529 * @return array
530 * an associative array of label, value pairs
531 */
532 public static function getOptionValuesAssocArrayFromName($optionGroupName) {
533 $dao = new CRM_Core_DAO_OptionGroup();
534 $dao->name = $optionGroupName;
535 $dao->selectAdd();
536 $dao->selectAdd('id');
537 $dao->find(TRUE);
538 $optionValues = self::getOptionValuesArray($dao->id);
539
540 $options = [];
541 foreach ($optionValues as $id => $value) {
542 $options[$value['value']] = $value['label'];
543 }
544 return $options;
545 }
546
547 /**
548 * Ensure an option value exists.
549 *
550 * This function is intended to be called from the upgrade script to ensure
551 * that an option value exists, without hitting an error if it already exists.
552 *
553 * This is sympathetic to sites who might pre-add it.
554 *
555 * @param array $params the option value attributes.
556 * @return array the option value attributes.
557 */
558 public static function ensureOptionValueExists($params) {
559 $result = civicrm_api3('OptionValue', 'get', [
560 'option_group_id' => $params['option_group_id'],
561 'name' => $params['name'],
562 'return' => ['id', 'value'],
563 'sequential' => 1,
564 ]);
565
566 if (!$result['count']) {
567 $result = civicrm_api3('OptionValue', 'create', $params);
568 }
569
570 return CRM_Utils_Array::first($result['values']);
571 }
572
573 }