Merge pull request #21470 from mattwire/templatecontributioncreate
[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 // action is taken depending upon the mode
159 $optionValue = new CRM_Core_DAO_OptionValue();
160 $optionValue->copyValues($params);
161
162 $isDomainOptionGroup = CRM_Core_OptionGroup::isDomainOptionGroup($groupName);
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']))) {
165 $optionValue->domain_id = CRM_Core_Config::domainID();
166 }
167
168 // When setting a default option, unset other options in this group as default
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'])) {
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
183 $p = [1 => [$params['option_group_id'], 'Integer']];
184
185 // Limit update by domain of option
186 $domain = CRM_Utils_System::isNull($optionValue->domain_id) ? NULL : $optionValue->domain_id;
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);
196 }
197
198 $groupsSupportingDuplicateValues = ['languages'];
199 if (!$id && !empty($params['value'])) {
200 $dao = new CRM_Core_DAO_OptionValue();
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 }
208 if (CRM_Core_OptionGroup::isDomainOptionGroup($groupName)) {
209 $dao->domain_id = $optionValue->domain_id;
210 }
211 $dao->option_group_id = $params['option_group_id'];
212 if ($dao->find(TRUE)) {
213 throw new CRM_Core_Exception('Value already exists in the database');
214 }
215 }
216
217 $optionValue->id = $id;
218 $optionValue->save();
219 CRM_Core_PseudoConstant::flush();
220
221 // Create relationship for payment instrument options
222 if (!empty($params['financial_account_id'])) {
223 $optionName = civicrm_api3('OptionGroup', 'getvalue', [
224 'return' => 'name',
225 'id' => $params['option_group_id'],
226 ]);
227 // Only create relationship for payment instrument options
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 }
243 return $optionValue;
244 }
245
246 /**
247 * Delete Option Value.
248 *
249 * @param int $optionValueId
250 *
251 * @return bool
252 *
253 */
254 public static function del($optionValueId) {
255 $optionValue = new CRM_Core_DAO_OptionValue();
256 $optionValue->id = $optionValueId;
257 if (!$optionValue->find()) {
258 return FALSE;
259 }
260 $hookParams = ['id' => $optionValueId];
261 CRM_Utils_Hook::pre('delete', 'OptionValue', $optionValueId, $hookParams);
262 if (self::updateRecords($optionValueId, CRM_Core_Action::DELETE)) {
263 CRM_Core_PseudoConstant::flush();
264 $optionValue->delete();
265 CRM_Utils_Hook::post('delete', 'OptionValue', $optionValueId, $optionValue);
266 return TRUE;
267 }
268 return FALSE;
269 }
270
271 /**
272 * Retrieve activity type label and description.
273 *
274 * @param int $activityTypeId
275 * Activity type id.
276 *
277 * @return array
278 * label and description
279 */
280 public static function getActivityTypeDetails($activityTypeId) {
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
291 return [$dao->label, $dao->description];
292 }
293
294 /**
295 * Get the Option Value title.
296 *
297 * @param int $id
298 * Id of Option Value.
299 *
300 * @return string
301 * title
302 *
303 */
304 public static function getTitle($id) {
305 return CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $id, 'label');
306 }
307
308 /**
309 * Updates contacts affected by the option value passed.
310 *
311 * @param int $optionValueId
312 * The option value id.
313 * @param int $action
314 * The action describing whether prefix/suffix was UPDATED or DELETED.
315 *
316 * @return bool
317 */
318 public static function updateRecords(&$optionValueId, $action) {
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
334 // todo: this may no longer be needed for individuals - check inputs
335 $individuals = [
336 'gender' => 'gender_id',
337 'individual_prefix' => 'prefix_id',
338 'individual_suffix' => 'suffix_id',
339 'communication_style' => 'communication_style_id',
340 // Not only Individuals -- but the code seems to be generic for all contact types, despite the naming...
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'];
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 /**
441 * Updates options values weights.
442 *
443 * @param int $opGroupId
444 * @param array $opWeights
445 * Options value , weight pair.
446 */
447 public static function updateOptionWeights($opGroupId, $opWeights) {
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 }
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 *
468 * @param int $optionGroupID
469 * The option group for which we want the values from.
470 *
471 * @return array
472 * an array of array of values for this option group
473 */
474 public static function getOptionValuesArray($optionGroupID) {
475 // check if we can get the field values from the system cache
476 $cacheKey = "CRM_Core_BAO_OptionValue_OptionGroupID_{$optionGroupID}";
477 $cache = CRM_Utils_Cache::singleton();
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
485 $optionValues = [];
486 while ($dao->fetch()) {
487 $optionValues[$dao->id] = [];
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 *
501 * @param int $optionGroupID
502 * The option group for which we want the values from.
503 *
504 * @return array
505 * an associative array of label, value pairs
506 */
507 public static function getOptionValuesAssocArray($optionGroupID) {
508 $optionValues = self::getOptionValuesArray($optionGroupID);
509
510 $options = [];
511 foreach ($optionValues as $id => $value) {
512 $options[$value['value']] = $value['label'];
513 }
514 return $options;
515 }
516
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 *
521 * @param string $optionGroupName
522 * The option group name for which we want the values from.
523 *
524 * @return array
525 * an associative array of label, value pairs
526 */
527 public static function getOptionValuesAssocArrayFromName($optionGroupName) {
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
535 $options = [];
536 foreach ($optionValues as $id => $value) {
537 $options[$value['value']] = $value['label'];
538 }
539 return $options;
540 }
541
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.
549 *
550 * @param array $params the option value attributes.
551 * @return array the option value attributes.
552 */
553 public static function ensureOptionValueExists($params) {
554 $result = civicrm_api3('OptionValue', 'get', [
555 'option_group_id' => $params['option_group_id'],
556 'name' => $params['name'],
557 'return' => ['id', 'value'],
558 'sequential' => 1,
559 ]);
560
561 if (!$result['count']) {
562 $result = civicrm_api3('OptionValue', 'create', $params);
563 }
564
565 return CRM_Utils_Array::first($result['values']);
566 }
567
568 }