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