Merge pull request #23970 from MegaphoneJon/false-not-zero
[civicrm-core.git] / CRM / Core / 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_OptionValue {
18
19 /**
20 * Static field for all the option value information that we can potentially export.
21 *
22 * @var array
23 */
24 public static $_exportableFields = NULL;
25
26 /**
27 * Static field for all the option value information that we can potentially export.
28 *
29 * @var array
30 */
31 public static $_importableFields = NULL;
32
33 /**
34 * Static field for all the option value information that we can potentially export.
35 *
36 * @var array
37 */
38 public static $_fields = NULL;
39
40 /**
41 * Return option-values of a particular group
42 *
43 * @param array $groupParams
44 * Array containing group fields whose option-values is to retrieved.
45 * @param array $links
46 * Has links like edit, delete, disable ..etc.
47 * @param string $orderBy
48 * For orderBy clause.
49 * @param bool $skipEmptyComponents
50 * Whether to skip OptionValue rows with empty Component name
51 * (i.e. when Extension providing the Component is disabled)
52 *
53 * @return array
54 * Array of option-values
55 *
56 */
57 public static function getRows($groupParams, $links, $orderBy = 'weight', $skipEmptyComponents = TRUE) {
58 $optionValue = [];
59 $optionGroupID = NULL;
60 $isGroupLocked = FALSE;
61
62 if (!isset($groupParams['id']) || !$groupParams['id']) {
63 if ($groupParams['name']) {
64 $optionGroup = CRM_Core_BAO_OptionGroup::retrieve($groupParams, $dnc);
65 $optionGroupID = $optionGroup->id;
66 $isGroupLocked = (bool) $optionGroup->is_locked;
67 }
68 }
69 else {
70 $optionGroupID = $groupParams['id'];
71 }
72
73 $groupName = $groupParams['name'] ?? NULL;
74 if (!$groupName && $optionGroupID) {
75 $groupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup',
76 $optionGroupID, 'name', 'id'
77 );
78 }
79
80 $dao = new CRM_Core_DAO_OptionValue();
81
82 if ($optionGroupID) {
83 $dao->option_group_id = $optionGroupID;
84
85 if (CRM_Core_OptionGroup::isDomainOptionGroup($groupName)) {
86 $dao->domain_id = CRM_Core_Config::domainID();
87 }
88
89 $dao->orderBy($orderBy);
90 $dao->find();
91 }
92
93 if ($groupName == 'case_type') {
94 $caseTypeIds = CRM_Case_BAO_Case::getUsedCaseType();
95 }
96 elseif ($groupName == 'case_status') {
97 $caseStatusIds = CRM_Case_BAO_Case::getUsedCaseStatuses();
98 }
99
100 $componentNames = CRM_Core_Component::getNames();
101 $visibilityLabels = CRM_Core_PseudoConstant::visibility();
102 while ($dao->fetch()) {
103 $optionValue[$dao->id] = [];
104 CRM_Core_DAO::storeValues($dao, $optionValue[$dao->id]);
105 if (!empty($optionValue[$dao->id]['component_id']) &&
106 empty($componentNames[$optionValue[$dao->id]['component_id']]) &&
107 $skipEmptyComponents
108 ) {
109 unset($optionValue[$dao->id]);
110 continue;
111 }
112 // form all action links
113 $action = array_sum(array_keys($links));
114
115 // update enable/disable links depending on if it is is_reserved or is_active
116 if ($dao->is_reserved) {
117 $action = CRM_Core_Action::UPDATE;
118 }
119 else {
120 if ($dao->is_active) {
121 $action -= CRM_Core_Action::ENABLE;
122 }
123 else {
124 $action -= CRM_Core_Action::DISABLE;
125 }
126 if ((($groupName == 'case_type') && in_array($dao->value, $caseTypeIds)) ||
127 (($groupName == 'case_status') && in_array($dao->value, $caseStatusIds))
128 ) {
129 $action -= CRM_Core_Action::DELETE;
130 }
131 }
132
133 // disallow deletion of option values for locked groups
134 if (($action & CRM_Core_Action::DELETE) && $isGroupLocked) {
135 $action -= CRM_Core_Action::DELETE;
136 }
137
138 $optionValue[$dao->id]['label'] = htmlspecialchars($optionValue[$dao->id]['label']);
139 $optionValue[$dao->id]['order'] = $optionValue[$dao->id]['weight'];
140 $optionValue[$dao->id]['icon'] = CRM_Utils_Array::value('icon', $optionValue[$dao->id], '');
141 $optionValue[$dao->id]['action'] = CRM_Core_Action::formLink($links, $action,
142 [
143 'id' => $dao->id,
144 'gid' => $optionGroupID,
145 'value' => $dao->value,
146 ],
147 ts('more'),
148 FALSE,
149 'optionValue.row.actions',
150 'optionValue',
151 $dao->id
152 );
153
154 if (!empty($optionValue[$dao->id]['component_id'])) {
155 $optionValue[$dao->id]['component_name'] = $componentNames[$optionValue[$dao->id]['component_id']];
156 }
157 else {
158 $optionValue[$dao->id]['component_name'] = 'Contact';
159 }
160
161 if (!empty($optionValue[$dao->id]['visibility_id'])) {
162 $optionValue[$dao->id]['visibility_label'] = $visibilityLabels[$optionValue[$dao->id]['visibility_id']];
163 }
164 }
165
166 return $optionValue;
167 }
168
169 /**
170 * Add/edit option-value of a particular group
171 *
172 * @param array $params
173 * Array containing exported values from the invoking form.
174 * @param string $optionGroupName
175 * Array containing group fields whose option-values is to retrieved/saved.
176 * @param $action
177 * @param int $optionValueID Has the id of the optionValue being edited, disabled ..etc.
178 * Has the id of the optionValue being edited, disabled ..etc.
179 *
180 * @return CRM_Core_DAO_OptionValue
181 *
182 */
183 public static function addOptionValue(&$params, $optionGroupName, $action, $optionValueID) {
184 $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
185 // checking if the group name with the given id or name (in $groupParams) exists
186 $groupParams = ['name' => $optionGroupName, 'is_active' => 1];
187 $optionGroup = CRM_Core_BAO_OptionGroup::retrieve($groupParams, $defaults);
188
189 // if the corresponding group doesn't exist, create one.
190 if (!$optionGroup->id) {
191 $newOptionGroup = CRM_Core_BAO_OptionGroup::add($groupParams);
192 $params['weight'] = 1;
193 $optionGroupID = $newOptionGroup->id;
194 }
195 else {
196 $optionGroupID = $optionGroup->id;
197 $oldWeight = NULL;
198 if ($optionValueID) {
199 $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'weight', 'id');
200 }
201 $fieldValues = ['option_group_id' => $optionGroupID];
202 $params['weight'] = CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_OptionValue', $oldWeight, CRM_Utils_Array::value('weight', $params), $fieldValues);
203 }
204 $params['option_group_id'] = $optionGroupID;
205
206 if (($action & CRM_Core_Action::ADD) && !isset($params['value'])) {
207 $fieldValues = ['option_group_id' => $optionGroupID];
208 // use the next available value
209 /* CONVERT(value, DECIMAL) is used to convert varchar
210 field 'value' to decimal->integer */
211
212 $params['value'] = (int) CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue',
213 $fieldValues,
214 'CONVERT(value, DECIMAL)'
215 );
216 }
217 if (!$params['label'] && $params['name']) {
218 $params['label'] = $params['name'];
219 }
220
221 // set name to label if it's not set - but *only* for ADD action (CRM-3522)
222 if (($action & CRM_Core_Action::ADD) && empty($params['name']) && $params['label']) {
223 $params['name'] = $params['label'];
224 }
225 if ($action & CRM_Core_Action::UPDATE) {
226 $params['id'] = $optionValueID;
227 }
228 $optionValue = CRM_Core_BAO_OptionValue::add($params);
229 return $optionValue;
230 }
231
232 /**
233 * Check if there is a record with the same name in the db.
234 *
235 * @param string $value
236 * The value of the field we are checking.
237 * @param string $daoName
238 * The dao object name.
239 * @param string $daoID
240 * The id of the object being updated. u can change your name.
241 * as long as there is no conflict
242 * @param int $optionGroupID
243 * @param string $fieldName
244 * The name of the field in the DAO.
245 * @param bool $domainSpecific
246 * Filter this check to the current domain.
247 * Some optionGroups allow for same labels or same names but
248 * they must be in different domains, so filter the check to
249 * the current domain.
250 *
251 * @return bool
252 * true if object exists
253 */
254 public static function optionExists($value, $daoName, $daoID, $optionGroupID, $fieldName, $domainSpecific) {
255 $object = new $daoName();
256 $object->$fieldName = $value;
257 $object->option_group_id = $optionGroupID;
258
259 if ($domainSpecific) {
260 $object->domain_id = CRM_Core_Config::domainID();
261 }
262
263 if ($object->find(TRUE)) {
264 return $daoID && $object->id == $daoID;
265 }
266 else {
267 return TRUE;
268 }
269 }
270
271 /**
272 * Check if there is a record with the same name in the db.
273 *
274 * @param string $mode
275 * @param string $contactType
276 *
277 * @return array
278 */
279 public static function getFields($mode = '', $contactType = 'Individual') {
280 $key = "$mode $contactType";
281 if (empty(self::$_fields[$key]) || !self::$_fields[$key]) {
282 self::$_fields[$key] = [];
283
284 $option = CRM_Core_DAO_OptionValue::import();
285
286 foreach (array_keys($option) as $id) {
287 $optionName = $option[$id];
288 }
289
290 $nameTitle = [];
291 if ($mode == 'contribute') {
292 // @todo - remove this - the only code place that calls
293 // this function in a way that would hit this is commented 'remove this'
294 // This is part of a move towards standardising option values but we
295 // should derive them from the fields array so am deprecating it again...
296 // note that the reason this was needed was that payment_instrument_id was
297 // not set to exportable.
298 $nameTitle = [
299 'payment_instrument' => [
300 'name' => 'payment_instrument',
301 'title' => ts('Payment Method'),
302 'headerPattern' => '/^payment|(p(ayment\s)?instrument)$/i',
303 ],
304 ];
305 }
306 elseif ($mode == '') {
307 //the fields email greeting and postal greeting are meant only for Individual and Household
308 //the field addressee is meant for all contact types, CRM-4575
309 if (in_array($contactType, [
310 'Individual',
311 'Household',
312 'Organization',
313 'All',
314 ])) {
315 $nameTitle = [
316 'addressee' => [
317 'name' => 'addressee',
318 'title' => ts('Addressee'),
319 'headerPattern' => '/^addressee$/i',
320 ],
321 ];
322 $title = [
323 'email_greeting' => [
324 'name' => 'email_greeting',
325 'title' => ts('Email Greeting'),
326 'headerPattern' => '/^email_greeting$/i',
327 ],
328 'postal_greeting' => [
329 'name' => 'postal_greeting',
330 'title' => ts('Postal Greeting'),
331 'headerPattern' => '/^postal_greeting$/i',
332 ],
333 ];
334 $nameTitle = array_merge($nameTitle, $title);
335 }
336 }
337
338 if (is_array($nameTitle)) {
339 foreach ($nameTitle as $name => $attribs) {
340 self::$_fields[$key][$name] = $optionName;
341 list($tableName, $fieldName) = explode('.', $optionName['where']);
342 self::$_fields[$key][$name]['where'] = "{$name}.label";
343 foreach ($attribs as $k => $val) {
344 self::$_fields[$key][$name][$k] = $val;
345 }
346 }
347 }
348 }
349
350 return self::$_fields[$key];
351 }
352
353 /**
354 * Build select query in case of option-values
355 *
356 * @param $query
357 */
358 public static function select(&$query) {
359 if (!empty($query->_params) || !empty($query->_returnProperties)) {
360 $field = self::getFields();
361 foreach ($field as $name => $values) {
362 if (!empty($values['pseudoconstant'])) {
363 continue;
364 }
365 list($tableName, $fieldName) = explode('.', $values['where']);
366 if (!empty($query->_returnProperties[$name])) {
367 $query->_select["{$name}_id"] = "{$name}.value as {$name}_id";
368 $query->_element["{$name}_id"] = 1;
369 $query->_select[$name] = "{$name}.{$fieldName} as $name";
370 $query->_tables[$tableName] = 1;
371 $query->_element[$name] = 1;
372 }
373 }
374 }
375 }
376
377 /**
378 * Return option-values of a particular group
379 *
380 * @param array $groupParams
381 * Array containing group fields.
382 * whose option-values is to retrieved.
383 * @param array $values
384 * (reference) to the array which.
385 * will have the values for the group
386 * @param string $orderBy
387 * For orderBy clause.
388 *
389 * @param bool $isActive Do you want only active option values?
390 *
391 * @return array
392 * Array of option-values
393 *
394 */
395 public static function getValues($groupParams, &$values = [], $orderBy = 'weight', $isActive = FALSE) {
396 if (empty($groupParams)) {
397 return NULL;
398 }
399 $select = "
400 SELECT
401 option_value.id as id,
402 option_value.label as label,
403 option_value.value as value,
404 option_value.name as name,
405 option_value.description as description,
406 option_value.weight as weight,
407 option_value.is_active as is_active,
408 option_value.icon as icon,
409 option_value.color as color,
410 option_value.is_default as is_default";
411
412 $from = "
413 FROM
414 civicrm_option_value as option_value,
415 civicrm_option_group as option_group ";
416
417 $where = " WHERE option_group.id = option_value.option_group_id ";
418
419 if ($isActive) {
420 $where .= " AND option_value.is_active = " . $isActive;
421 }
422
423 $order = " ORDER BY " . $orderBy;
424
425 $groupId = $groupParams['id'] ?? NULL;
426 $groupName = $groupParams['name'] ?? NULL;
427
428 if ($groupId) {
429 $where .= " AND option_group.id = %1";
430 $params[1] = [$groupId, 'Integer'];
431 if (!$groupName) {
432 $groupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup',
433 $groupId, 'name', 'id'
434 );
435 }
436 }
437
438 if ($groupName) {
439 $where .= " AND option_group.name = %2";
440 $params[2] = [$groupName, 'String'];
441 }
442
443 if (CRM_Core_OptionGroup::isDomainOptionGroup($groupName)) {
444 $where .= " AND option_value.domain_id = " . CRM_Core_Config::domainID();
445 }
446
447 $query = $select . $from . $where . $order;
448
449 $dao = CRM_Core_DAO::executeQuery($query, $params);
450
451 while ($dao->fetch()) {
452 $values[$dao->id] = [
453 'id' => $dao->id,
454 'label' => $dao->label,
455 'value' => $dao->value,
456 'name' => $dao->name,
457 'description' => $dao->description,
458 'weight' => $dao->weight,
459 'is_active' => $dao->is_active,
460 'is_default' => $dao->is_default,
461 'icon' => $dao->icon,
462 'color' => $dao->color,
463 ];
464 }
465 return $values;
466 }
467
468 }