APIv4 - Add SortableEntity and ManagedEntity traits to Navigation menu entity
[civicrm-core.git] / Civi / Api4 / Generic / Traits / DAOActionTrait.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
6 | |
7 | This work is published under the GNU AGPLv3 license with some |
8 | permitted exceptions and without any warranty. For full license |
9 | and copyright information, see https://civicrm.org/licensing |
10 +--------------------------------------------------------------------+
11 */
12
13 namespace Civi\Api4\Generic\Traits;
14
15 use Civi\Api4\CustomField;
16 use Civi\Api4\Service\Schema\Joinable\CustomGroupJoinable;
17 use Civi\Api4\Utils\FormattingUtil;
18 use Civi\Api4\Utils\CoreUtil;
19
20 /**
21 * @method string getLanguage()
22 * @method $this setLanguage(string $language)
23 */
24 trait DAOActionTrait {
25
26 /**
27 * Specify the language to use if this is a multi-lingual environment.
28 *
29 * E.g. "en_US" or "fr_CA"
30 *
31 * @var string
32 */
33 protected $language;
34
35 private $_maxWeights = [];
36
37 /**
38 * @return \CRM_Core_DAO|string
39 */
40 protected function getBaoName() {
41 return CoreUtil::getBAOFromApiName($this->getEntityName());
42 }
43
44 /**
45 * Convert saved object to array
46 *
47 * Used by create, update & save actions
48 *
49 * @param \CRM_Core_DAO $bao
50 * @param array $input
51 * @return array
52 */
53 public function baoToArray($bao, $input) {
54 $allFields = array_column($bao->fields(), 'name');
55 if (!empty($this->reload)) {
56 $inputFields = $allFields;
57 $bao->find(TRUE);
58 }
59 else {
60 $inputFields = array_keys($input);
61 // Convert 'null' input to true null
62 foreach ($input as $key => $val) {
63 if ($val === 'null') {
64 $bao->$key = NULL;
65 }
66 }
67 }
68 $values = [];
69 foreach ($allFields as $field) {
70 if (isset($bao->$field) || in_array($field, $inputFields)) {
71 $values[$field] = $bao->$field ?? NULL;
72 }
73 }
74 return $values;
75 }
76
77 /**
78 * Fill field defaults which were declared by the api.
79 *
80 * Note: default values from core are ignored because the BAO or database layer will supply them.
81 *
82 * @param array $params
83 */
84 protected function fillDefaults(&$params) {
85 $fields = $this->entityFields();
86 $bao = $this->getBaoName();
87 $coreFields = array_column($bao::fields(), NULL, 'name');
88
89 foreach ($fields as $name => $field) {
90 // If a default value in the api field is different than in core, the api should override it.
91 if (!isset($params[$name]) && !empty($field['default_value']) && $field['default_value'] != \CRM_Utils_Array::pathGet($coreFields, [$name, 'default'])) {
92 $params[$name] = $field['default_value'];
93 }
94 }
95 }
96
97 /**
98 * Write bao objects as part of a create/update action.
99 *
100 * @param array $items
101 * The records to write to the DB.
102 *
103 * @return array
104 * The records after being written to the DB (e.g. including newly assigned "id").
105 * @throws \API_Exception
106 * @throws \CRM_Core_Exception
107 */
108 protected function writeObjects(&$items) {
109 $baoName = $this->getBaoName();
110 $updateWeights = FALSE;
111
112 // TODO: Opt-in more entities to use the new writeRecords BAO method.
113 $functionNames = [
114 'Address' => 'add',
115 'CustomField' => 'writeRecords',
116 'EntityTag' => 'add',
117 'GroupContact' => 'add',
118 'Navigation' => 'writeRecords',
119 ];
120 $method = $functionNames[$this->getEntityName()] ?? NULL;
121 if (!isset($method)) {
122 $method = method_exists($baoName, 'create') ? 'create' : (method_exists($baoName, 'add') ? 'add' : 'writeRecords');
123 }
124
125 // Adjust weights for sortable entities
126 if (in_array('SortableEntity', CoreUtil::getInfoItem($this->getEntityName(), 'type'))) {
127 $weightField = CoreUtil::getInfoItem($this->getEntityName(), 'order_by');
128 // Only take action if updating a single record, or if no weights are specified in any record
129 // This avoids messing up a bulk update with multiple recalculations
130 if (count($items) === 1 || !array_filter(array_column($items, $weightField))) {
131 $updateWeights = TRUE;
132 }
133 }
134
135 $result = [];
136
137 foreach ($items as &$item) {
138 $entityId = $item['id'] ?? NULL;
139 FormattingUtil::formatWriteParams($item, $this->entityFields());
140 $this->formatCustomParams($item, $entityId);
141
142 // Adjust weights for sortable entities
143 if ($updateWeights) {
144 $this->updateWeight($item);
145 }
146
147 // Skip individual processing if using writeRecords
148 if ($method === 'writeRecords') {
149 continue;
150 }
151 $item['check_permissions'] = $this->getCheckPermissions();
152
153 // For some reason the contact bao requires this
154 if ($entityId && $this->getEntityName() === 'Contact') {
155 $item['contact_id'] = $entityId;
156 }
157
158 if ($this->getEntityName() === 'Address') {
159 $createResult = $baoName::$method($item, $this->fixAddress);
160 }
161 else {
162 $createResult = $baoName::$method($item);
163 }
164
165 if (!$createResult) {
166 $errMessage = sprintf('%s write operation failed', $this->getEntityName());
167 throw new \API_Exception($errMessage);
168 }
169
170 $result[] = $this->baoToArray($createResult, $item);
171 \CRM_Utils_API_HTMLInputCoder::singleton()->decodeRows($result);
172 }
173
174 // Use bulk `writeRecords` method if the BAO doesn't have a create or add method
175 // TODO: reverse this from opt-in to opt-out and default to using `writeRecords` for all BAOs
176 if ($method === 'writeRecords') {
177 $items = array_values($items);
178 foreach ($baoName::writeRecords($items) as $i => $createResult) {
179 $result[] = $this->baoToArray($createResult, $items[$i]);
180 }
181 }
182
183 FormattingUtil::formatOutputValues($result, $this->entityFields());
184 return $result;
185 }
186
187 /**
188 * @inheritDoc
189 */
190 protected function formatWriteValues(&$record) {
191 $this->resolveFKValues($record);
192 parent::formatWriteValues($record);
193 }
194
195 /**
196 * Looks up an id based on some other property of an fk entity
197 *
198 * @param array $record
199 */
200 private function resolveFKValues(array &$record): void {
201 foreach ($record as $key => $value) {
202 if (substr_count($key, '.') !== 1) {
203 continue;
204 }
205 [$fieldName, $fkField] = explode('.', $key);
206 $field = $this->entityFields()[$fieldName] ?? NULL;
207 if (!$field || empty($field['fk_entity'])) {
208 continue;
209 }
210 $fkDao = CoreUtil::getBAOFromApiName($field['fk_entity']);
211 $record[$fieldName] = \CRM_Core_DAO::getFieldValue($fkDao, $value, 'id', $fkField);
212 unset($record[$key]);
213 }
214 }
215
216 /**
217 * Converts params from flat array e.g. ['GroupName.Fieldname' => value] to the
218 * hierarchy expected by the BAO, nested within $params['custom'].
219 *
220 * @param array $params
221 * @param int $entityId
222 *
223 * @throws \API_Exception
224 * @throws \CRM_Core_Exception
225 */
226 protected function formatCustomParams(&$params, $entityId) {
227 $customParams = [];
228
229 foreach ($params as $name => $value) {
230 $field = $this->getCustomFieldInfo($name);
231 if (!$field) {
232 continue;
233 }
234
235 // todo are we sure we don't want to allow setting to NULL? need to test
236 if (NULL !== $value) {
237
238 if ($field['suffix']) {
239 $options = FormattingUtil::getPseudoconstantList($field, $name, $params, $this->getActionName());
240 $value = FormattingUtil::replacePseudoconstant($options, $value, TRUE);
241 }
242
243 if ($field['html_type'] === 'CheckBox') {
244 // this function should be part of a class
245 formatCheckBoxField($value, 'custom_' . $field['id'], $this->getEntityName());
246 }
247
248 // Match contact id to strings like "user_contact_id"
249 // FIXME handle arrays for multi-value contact reference fields, etc.
250 if ($field['data_type'] === 'ContactReference' && is_string($value) && !is_numeric($value)) {
251 // FIXME decouple from v3 API
252 require_once 'api/v3/utils.php';
253 $value = \_civicrm_api3_resolve_contactID($value);
254 if ('unknown-user' === $value) {
255 throw new \API_Exception("\"{$field['name']}\" \"{$value}\" cannot be resolved to a contact ID", 2002, ['error_field' => $field['name'], "type" => "integer"]);
256 }
257 }
258
259 \CRM_Core_BAO_CustomField::formatCustomField(
260 $field['id'],
261 $customParams,
262 $value,
263 $field['custom_group_id.extends'],
264 // todo check when this is needed
265 NULL,
266 $entityId,
267 FALSE,
268 $this->getCheckPermissions(),
269 TRUE
270 );
271 }
272 }
273
274 $params['custom'] = $customParams ?: NULL;
275 }
276
277 /**
278 * Gets field info needed to save custom data
279 *
280 * @param string $fieldExpr
281 * Field identifier with possible suffix, e.g. MyCustomGroup.MyField1:label
282 * @return array{id: int, name: string, entity: string, suffix: string, html_type: string, data_type: string}|NULL
283 */
284 protected function getCustomFieldInfo(string $fieldExpr) {
285 if (strpos($fieldExpr, '.') === FALSE) {
286 return NULL;
287 }
288 [$groupName, $fieldName] = explode('.', $fieldExpr);
289 [$fieldName, $suffix] = array_pad(explode(':', $fieldName), 2, NULL);
290 $cacheKey = "APIv4_Custom_Fields-$groupName";
291 $info = \Civi::cache('metadata')->get($cacheKey);
292 if (!isset($info[$fieldName])) {
293 $info = [];
294 $fields = CustomField::get(FALSE)
295 ->addSelect('id', 'name', 'html_type', 'data_type', 'custom_group_id.extends')
296 ->addWhere('custom_group_id.name', '=', $groupName)
297 ->execute()->indexBy('name');
298 foreach ($fields as $name => $field) {
299 $field['custom_field_id'] = $field['id'];
300 $field['name'] = $groupName . '.' . $name;
301 $field['entity'] = CustomGroupJoinable::getEntityFromExtends($field['custom_group_id.extends']);
302 $info[$name] = $field;
303 }
304 \Civi::cache('metadata')->set($cacheKey, $info);
305 }
306 return isset($info[$fieldName]) ? ['suffix' => $suffix] + $info[$fieldName] : NULL;
307 }
308
309 /**
310 * Update weights when inserting or updating a sortable entity
311 * @param array $record
312 * @see SortableEntity
313 */
314 protected function updateWeight(array &$record) {
315 /** @var \CRM_Core_DAO|string $daoName */
316 $daoName = CoreUtil::getInfoItem($this->getEntityName(), 'dao');
317 $weightField = CoreUtil::getInfoItem($this->getEntityName(), 'order_by');
318 $idField = CoreUtil::getIdFieldName($this->getEntityName());
319 // If updating an existing record without changing weight, do nothing
320 if (!isset($record[$weightField]) && !empty($record[$idField])) {
321 return;
322 }
323 $daoFields = $daoName::getSupportedFields();
324 $newWeight = $record[$weightField] ?? NULL;
325 $oldWeight = empty($record[$idField]) ? NULL : \CRM_Core_DAO::getFieldValue($daoName, $record[$idField], $weightField);
326
327 // FIXME: Need a more metadata-ish approach. For now here's a hardcoded list of the fields sortable entities use for grouping.
328 $guesses = ['option_group_id', 'price_set_id', 'price_field_id', 'premiums_id', 'uf_group_id', 'custom_group_id', 'parent_id', 'domain_id'];
329 $filters = [];
330 foreach (array_intersect($guesses, array_keys($daoFields)) as $filter) {
331 $filters[$filter] = $record[$filter] ?? (empty($record[$idField]) ? NULL : \CRM_Core_DAO::getFieldValue($daoName, $record[$idField], $filter));
332 }
333 // Supply default weight for new record
334 if (!isset($record[$weightField]) && empty($record[$idField])) {
335 $record[$weightField] = $this->getMaxWeight($daoName, $filters, $weightField);
336 }
337 else {
338 $record[$weightField] = \CRM_Utils_Weight::updateOtherWeights($daoName, $oldWeight, $newWeight, $filters, $weightField);
339 }
340 }
341
342 /**
343 * Looks up max weight for a set of sortable entities
344 *
345 * Keeps it in memory in case this operation is writing more than one record
346 *
347 * @param $daoName
348 * @param $filters
349 * @param $weightField
350 * @return int|mixed
351 */
352 private function getMaxWeight($daoName, $filters, $weightField) {
353 $key = $daoName . json_encode($filters);
354 if (!isset($this->_maxWeights[$key])) {
355 $this->_maxWeights[$key] = \CRM_Utils_Weight::getMax($daoName, $filters, $weightField) + 1;
356 }
357 else {
358 ++$this->_maxWeights[$key];
359 }
360 return $this->_maxWeights[$key];
361 }
362
363 }