APIv4 - Default to saving and deleting DAO records in bulk
[civicrm-core.git] / Civi / Api4 / Generic / Traits / DAOActionTrait.php
CommitLineData
19b53e5b 1<?php
380f3545
TO
2
3/*
4 +--------------------------------------------------------------------+
41498ac5 5 | Copyright CiviCRM LLC. All rights reserved. |
380f3545 6 | |
41498ac5
TO
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 |
380f3545
TO
10 +--------------------------------------------------------------------+
11 */
12
19b53e5b
C
13namespace Civi\Api4\Generic\Traits;
14
c9e3994d 15use Civi\Api4\CustomField;
721c9da1 16use Civi\Api4\Service\Schema\Joinable\CustomGroupJoinable;
19b53e5b 17use Civi\Api4\Utils\FormattingUtil;
a62d97f3 18use Civi\Api4\Utils\CoreUtil;
19b53e5b
C
19
20/**
21 * @method string getLanguage()
14a9c588 22 * @method $this setLanguage(string $language)
19b53e5b
C
23 */
24trait 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 /**
36 * @return \CRM_Core_DAO|string
37 */
38 protected function getBaoName() {
a62d97f3 39 return CoreUtil::getBAOFromApiName($this->getEntityName());
19b53e5b
C
40 }
41
42 /**
a4c7afc0 43 * Convert saved object to array
19b53e5b 44 *
a4c7afc0
CW
45 * Used by create, update & save actions
46 *
47 * @param \CRM_Core_DAO $bao
48 * @param array $input
19b53e5b
C
49 * @return array
50 */
a4c7afc0
CW
51 public function baoToArray($bao, $input) {
52 $allFields = array_column($bao->fields(), 'name');
53 if (!empty($this->reload)) {
54 $inputFields = $allFields;
55 $bao->find(TRUE);
56 }
57 else {
58 $inputFields = array_keys($input);
59 // Convert 'null' input to true null
60 foreach ($input as $key => $val) {
61 if ($val === 'null') {
62 $bao->$key = NULL;
63 }
64 }
65 }
19b53e5b 66 $values = [];
a4c7afc0
CW
67 foreach ($allFields as $field) {
68 if (isset($bao->$field) || in_array($field, $inputFields)) {
69 $values[$field] = $bao->$field ?? NULL;
19b53e5b
C
70 }
71 }
72 return $values;
73 }
74
19b53e5b
C
75 /**
76 * Fill field defaults which were declared by the api.
77 *
78 * Note: default values from core are ignored because the BAO or database layer will supply them.
79 *
80 * @param array $params
81 */
82 protected function fillDefaults(&$params) {
83 $fields = $this->entityFields();
84 $bao = $this->getBaoName();
85 $coreFields = array_column($bao::fields(), NULL, 'name');
86
87 foreach ($fields as $name => $field) {
88 // If a default value in the api field is different than in core, the api should override it.
89 if (!isset($params[$name]) && !empty($field['default_value']) && $field['default_value'] != \CRM_Utils_Array::pathGet($coreFields, [$name, 'default'])) {
90 $params[$name] = $field['default_value'];
91 }
92 }
93 }
94
95 /**
96 * Write bao objects as part of a create/update action.
97 *
98 * @param array $items
99 * The records to write to the DB.
14a9c588 100 *
19b53e5b
C
101 * @return array
102 * The records after being written to the DB (e.g. including newly assigned "id").
103 * @throws \API_Exception
14a9c588 104 * @throws \CRM_Core_Exception
19b53e5b 105 */
baf63a69 106 protected function writeObjects(&$items) {
19b53e5b
C
107 $baoName = $this->getBaoName();
108
109 // Some BAOs are weird and don't support a straightforward "create" method.
110 $oddballs = [
236f858e 111 'Address' => 'add',
19b53e5b
C
112 'EntityTag' => 'add',
113 'GroupContact' => 'add',
19b53e5b
C
114 ];
115 $method = $oddballs[$this->getEntityName()] ?? 'create';
116 if (!method_exists($baoName, $method)) {
236f858e 117 $method = method_exists($baoName, 'add') ? 'add' : FALSE;
19b53e5b
C
118 }
119
120 $result = [];
121
baf63a69 122 foreach ($items as &$item) {
2929a8fb 123 $entityId = $item['id'] ?? NULL;
37d82abe 124 FormattingUtil::formatWriteParams($item, $this->entityFields());
19b53e5b 125 $this->formatCustomParams($item, $entityId);
236f858e
CW
126
127 // Skip to writeRecords if not using legacy method
128 if (!$method) {
129 continue;
130 }
19b53e5b
C
131 $item['check_permissions'] = $this->getCheckPermissions();
132
133 // For some reason the contact bao requires this
14a9c588 134 if ($entityId && $this->getEntityName() === 'Contact') {
19b53e5b
C
135 $item['contact_id'] = $entityId;
136 }
137
138 if ($this->getCheckPermissions()) {
139 $this->checkContactPermissions($baoName, $item);
140 }
141
14a9c588 142 if ($this->getEntityName() === 'Address') {
1db5a675 143 $createResult = $baoName::$method($item, $this->fixAddress);
19b53e5b 144 }
19b53e5b 145 else {
236f858e 146 $createResult = $baoName::$method($item);
19b53e5b
C
147 }
148
149 if (!$createResult) {
150 $errMessage = sprintf('%s write operation failed', $this->getEntityName());
151 throw new \API_Exception($errMessage);
152 }
153
a4c7afc0 154 $result[] = $this->baoToArray($createResult, $item);
19b53e5b 155 }
236f858e
CW
156
157 // Use bulk `writeRecords` method if the BAO doesn't have a create or add method
158 // TODO: reverse this from opt-in to opt-out and default to using `writeRecords` for all BAOs
159 if (!$method) {
160 $items = array_values($items);
161 foreach ($baoName::writeRecords($items) as $i => $createResult) {
162 $result[] = $this->baoToArray($createResult, $items[$i]);
163 }
164 }
165
2929a8fb 166 FormattingUtil::formatOutputValues($result, $this->entityFields(), $this->getEntityName());
19b53e5b
C
167 return $result;
168 }
169
19b53e5b
C
170 /**
171 * @param array $params
172 * @param int $entityId
14a9c588 173 *
14a9c588 174 * @throws \API_Exception
175 * @throws \CRM_Core_Exception
19b53e5b
C
176 */
177 protected function formatCustomParams(&$params, $entityId) {
178 $customParams = [];
179
180 // $customValueID is the ID of the custom value in the custom table for this
181 // entity (i guess this assumes it's not a multi value entity)
182 foreach ($params as $name => $value) {
c9e3994d
CW
183 $field = $this->getCustomFieldInfo($name);
184 if (!$field) {
19b53e5b
C
185 continue;
186 }
187
19b53e5b 188 // todo are we sure we don't want to allow setting to NULL? need to test
c9e3994d 189 if (NULL !== $value) {
19b53e5b 190
c9e3994d 191 if ($field['suffix']) {
721c9da1 192 $options = FormattingUtil::getPseudoconstantList($field, $field['suffix'], $params, $this->getActionName());
961e974c
CW
193 $value = FormattingUtil::replacePseudoconstant($options, $value, TRUE);
194 }
195
c9e3994d 196 if ($field['html_type'] === 'CheckBox') {
19b53e5b 197 // this function should be part of a class
c9e3994d 198 formatCheckBoxField($value, 'custom_' . $field['id'], $this->getEntityName());
19b53e5b
C
199 }
200
a6a158e7
CW
201 if ($field['data_type'] === 'ContactReference' && !is_numeric($value)) {
202 require_once 'api/v3/utils.php';
203 $value = \_civicrm_api3_resolve_contactID($value);
204 if ('unknown-user' === $value) {
205 throw new \API_Exception("\"{$field['name']}\" \"{$value}\" cannot be resolved to a contact ID", 2002, ['error_field' => $field['name'], "type" => "integer"]);
206 }
207 }
208
19b53e5b 209 \CRM_Core_BAO_CustomField::formatCustomField(
c9e3994d 210 $field['id'],
19b53e5b
C
211 $customParams,
212 $value,
c9e3994d 213 $field['custom_group.extends'],
19b53e5b
C
214 // todo check when this is needed
215 NULL,
216 $entityId,
217 FALSE,
218 FALSE,
219 TRUE
220 );
221 }
222 }
223
224 if ($customParams) {
225 $params['custom'] = $customParams;
226 }
227 }
228
c9e3994d
CW
229 /**
230 * Gets field info needed to save custom data
231 *
721c9da1 232 * @param string $fieldExpr
c9e3994d
CW
233 * Field identifier with possible suffix, e.g. MyCustomGroup.MyField1:label
234 * @return array|NULL
235 */
721c9da1
CW
236 protected function getCustomFieldInfo(string $fieldExpr) {
237 if (strpos($fieldExpr, '.') === FALSE) {
c9e3994d
CW
238 return NULL;
239 }
721c9da1 240 list($groupName, $fieldName) = explode('.', $fieldExpr);
c9e3994d 241 list($fieldName, $suffix) = array_pad(explode(':', $fieldName), 2, NULL);
721c9da1
CW
242 $cacheKey = "APIv4_Custom_Fields-$groupName";
243 $info = \Civi::cache('metadata')->get($cacheKey);
244 if (!isset($info[$fieldName])) {
245 $info = [];
246 $fields = CustomField::get(FALSE)
a6a158e7 247 ->addSelect('id', 'name', 'html_type', 'data_type', 'custom_group.extends')
c9e3994d
CW
248 ->addWhere('custom_group.name', '=', $groupName)
249 ->execute()->indexBy('name');
721c9da1
CW
250 foreach ($fields as $name => $field) {
251 $field['custom_field_id'] = $field['id'];
252 $field['name'] = $groupName . '.' . $name;
253 $field['entity'] = CustomGroupJoinable::getEntityFromExtends($field['custom_group.extends']);
254 $info[$name] = $field;
255 }
256 \Civi::cache('metadata')->set($cacheKey, $info);
c9e3994d 257 }
721c9da1 258 return isset($info[$fieldName]) ? ['suffix' => $suffix] + $info[$fieldName] : NULL;
c9e3994d
CW
259 }
260
19b53e5b
C
261 /**
262 * Check edit/delete permissions for contacts and related entities.
263 *
14a9c588 264 * @param string $baoName
265 * @param array $item
266 *
19b53e5b
C
267 * @throws \Civi\API\Exception\UnauthorizedException
268 */
269 protected function checkContactPermissions($baoName, $item) {
14a9c588 270 if ($baoName === 'CRM_Contact_BAO_Contact' && !empty($item['id'])) {
271 $permission = $this->getActionName() === 'delete' ? \CRM_Core_Permission::DELETE : \CRM_Core_Permission::EDIT;
19b53e5b
C
272 if (!\CRM_Contact_BAO_Contact_Permission::allow($item['id'], $permission)) {
273 throw new \Civi\API\Exception\UnauthorizedException('Permission denied to modify contact record');
274 }
275 }
276 else {
277 // Fixme: decouple from v3
278 require_once 'api/v3/utils.php';
2ee9afab 279 _civicrm_api3_check_edit_permissions($baoName, $item);
19b53e5b
C
280 }
281 }
282
283}