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