Merge pull request #24117 from civicrm/5.52
[civicrm-core.git] / Civi / Api4 / Generic / ExportAction.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;
14
15 use Civi\API\Exception\NotImplementedException;
16 use Civi\Api4\Utils\CoreUtil;
17
18 /**
19 * Export $ENTITY to civicrm_managed format.
20 *
21 * This action generates an exportable array suitable for use in a .mgd.php file.
22 * The array will include any other entities that reference the $ENTITY.
23 *
24 * @method $this setId(int $id)
25 * @method int getId()
26 * @method $this setCleanup(string $cleanup)
27 * @method string getCleanup()
28 * @method $this setUpdate(string $update)
29 * @method string getUpdate()
30 */
31 class ExportAction extends AbstractAction {
32
33 /**
34 * Id of $ENTITY to export
35 * @var int
36 * @required
37 */
38 protected $id;
39
40 /**
41 * Specify rule for auto-updating managed entity
42 * @var string
43 * @options never,always,unmodified
44 */
45 protected $update = 'unmodified';
46
47 /**
48 * Specify rule for auto-deleting managed entity
49 * @var string
50 * @options never,always,unused
51 */
52 protected $cleanup = 'unused';
53
54 /**
55 * Used to prevent circular references
56 * @var array
57 */
58 private $exportedEntities = [];
59
60 /**
61 * @param \Civi\Api4\Generic\Result $result
62 */
63 public function _run(Result $result) {
64 $this->exportRecord($this->getEntityName(), $this->id, $result);
65 }
66
67 /**
68 * @param string $entityType
69 * @param int $entityId
70 * @param \Civi\Api4\Generic\Result $result
71 * @param string $parentName
72 * @param array $excludeFields
73 */
74 private function exportRecord(string $entityType, int $entityId, Result $result, $parentName = NULL, $excludeFields = []) {
75 if (isset($this->exportedEntities[$entityType][$entityId])) {
76 throw new \API_Exception("Circular reference detected: attempted to export $entityType id $entityId multiple times.");
77 }
78 $this->exportedEntities[$entityType][$entityId] = TRUE;
79 $select = $pseudofields = [];
80 $allFields = $this->getFieldsForExport($entityType, TRUE, $excludeFields);
81 foreach ($allFields as $field) {
82 // Use implicit join syntax but only if the fk entity has a `name` field
83 if (!empty($field['fk_entity']) && array_key_exists('name', $this->getFieldsForExport($field['fk_entity']))) {
84 $select[] = $field['name'];
85 $select[] = $field['name'] . '.name';
86 $pseudofields[$field['name'] . '.name'] = $field['name'];
87 }
88 // Use pseudoconstant syntax if appropriate
89 elseif ($this->shouldUsePseudoconstant($entityType, $field)) {
90 $select[] = $field['name'];
91 $select[] = $field['name'] . ':name';
92 $pseudofields[$field['name'] . ':name'] = $field['name'];
93 }
94 elseif (empty($field['fk_entity'])) {
95 $select[] = $field['name'];
96 }
97 }
98 $record = civicrm_api4($entityType, 'get', [
99 'checkPermissions' => $this->checkPermissions,
100 'select' => $select,
101 'where' => [['id', '=', $entityId]],
102 ])->first();
103 if (!$record) {
104 return;
105 }
106 // The get api always returns ID, but it should not be included in an export
107 unset($record['id']);
108 // Should references be limited to the current domain?
109 $limitRefsByDomain = $entityType === 'OptionGroup' && \CRM_Core_OptionGroup::isDomainOptionGroup($record['name']) ? \CRM_Core_BAO_Domain::getDomain()->id : FALSE;
110 foreach ($allFields as $fieldName => $field) {
111 if (($field['fk_entity'] ?? NULL) === 'Domain') {
112 $alias = $fieldName . '.name';
113 if (isset($record[$alias])) {
114 // If this entity is for a specific domain, limit references to that same domain
115 if ($fieldName === 'domain_id') {
116 $limitRefsByDomain = \CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $record[$alias], 'id', 'name');
117 }
118 // Swap current domain for special API keyword
119 if ($record[$alias] === \CRM_Core_BAO_Domain::getDomain()->name) {
120 unset($record[$alias]);
121 $record[$fieldName] = 'current_domain';
122 }
123 }
124 }
125 }
126 $name = ($parentName ?? '') . $entityType . '_' . ($record['name'] ?? count($this->exportedEntities[$entityType]));
127 // Ensure safe characters, max length
128 $name = \CRM_Utils_String::munge($name, '_', 127);
129 // Include option group with custom field
130 if ($entityType === 'CustomField') {
131 if (
132 !empty($record['option_group_id.name']) &&
133 // Sometimes fields share an option group; only export it once.
134 empty($this->exportedEntities['OptionGroup'][$record['option_group_id']])
135 ) {
136 $this->exportRecord('OptionGroup', $record['option_group_id'], $result);
137 }
138 }
139 // Don't use joins/pseudoconstants if null or if it has the same value as the original
140 foreach ($pseudofields as $alias => $fieldName) {
141 if (!isset($record[$alias]) || $record[$alias] == ($record[$fieldName] ?? NULL)) {
142 unset($record[$alias]);
143 }
144 else {
145 unset($record[$fieldName]);
146 }
147 }
148 $result[] = [
149 'name' => $name,
150 'entity' => $entityType,
151 'cleanup' => $this->cleanup,
152 'update' => $this->update,
153 'params' => [
154 'version' => 4,
155 'values' => $record,
156 ],
157 ];
158 // Export entities that reference this one
159 $daoName = CoreUtil::getInfoItem($entityType, 'dao');
160 if ($daoName) {
161 /** @var \CRM_Core_DAO $dao */
162 $dao = $daoName::findById($entityId);
163 // Collect references into arrays keyed by entity type
164 $references = [];
165 foreach ($dao->findReferences() as $reference) {
166 $refEntity = \CRM_Utils_Array::first($reference::fields())['entity'] ?? '';
167 // Custom fields don't really "belong" to option groups despite the reference
168 if ($refEntity === 'CustomField' && $entityType === 'OptionGroup') {
169 continue;
170 }
171 // Limit references by domain
172 if (property_exists($reference, 'domain_id')) {
173 if (!isset($reference->domain_id)) {
174 $reference->find(TRUE);
175 }
176 if (isset($reference->domain_id) && $reference->domain_id != $limitRefsByDomain) {
177 continue;
178 }
179 }
180 $references[$refEntity][] = $reference;
181 }
182 foreach ($references as $refEntity => $records) {
183 $refApiType = CoreUtil::getInfoItem($refEntity, 'type') ?? [];
184 // Reference must be a ManagedEntity
185 if (!in_array('ManagedEntity', $refApiType, TRUE)) {
186 continue;
187 }
188 $exclude = [];
189 // For sortable entities, order by weight and exclude weight from the export (it will be auto-managed)
190 if (in_array('SortableEntity', $refApiType, TRUE)) {
191 $exclude[] = $weightCol = CoreUtil::getInfoItem($refEntity, 'order_by');
192 usort($records, function ($a, $b) use ($weightCol) {
193 if (!isset($a->$weightCol)) {
194 $a->find(TRUE);
195 }
196 if (!isset($b->$weightCol)) {
197 $b->find(TRUE);
198 }
199 return $a->$weightCol < $b->$weightCol ? -1 : 1;
200 });
201 }
202 foreach ($records as $record) {
203 $this->exportRecord($refEntity, $record->id, $result, $name . '_', $exclude);
204 }
205 }
206 }
207 }
208
209 /**
210 * If a field has a pseudoconstant list, determine whether it would be better
211 * to use pseudoconstant (field:name) syntax vs plain value.
212 *
213 * @param string $entityType
214 * @param array $field
215 * @return bool
216 */
217 private function shouldUsePseudoconstant(string $entityType, array $field) {
218 if (empty($field['options'])) {
219 return FALSE;
220 }
221 $daoName = CoreUtil::getInfoItem($entityType, 'dao');
222 // Exception for Profile.field_name
223 if ($entityType === 'UFField' && $field['name'] === 'field_name') {
224 return TRUE;
225 }
226 // Options generated by a callback function tend to be stable,
227 // and the :name property may not be reliable. Use plain value.
228 if ($daoName && !empty($daoName::getSupportedFields()[$field['name']]['pseudoconstant']['callback'])) {
229 return FALSE;
230 }
231 // Options with numeric keys probably refer to auto-increment keys
232 // which vary across different databases. Use :name syntax.
233 $numericKeys = array_filter(array_keys($field['options']), 'is_numeric');
234 return count($numericKeys) === count($field['options']);
235 }
236
237 /**
238 * @param $entityType
239 * @param bool $loadOptions
240 * @param array $excludeFields
241 * @return array
242 */
243 private function getFieldsForExport($entityType, $loadOptions = FALSE, $excludeFields = []): array {
244 $conditions = [
245 ['type', 'IN', ['Field', 'Custom']],
246 ['readonly', '!=', TRUE],
247 ];
248 if ($excludeFields) {
249 $conditions[] = ['name', 'NOT IN', $excludeFields];
250 }
251 try {
252 return (array) civicrm_api4($entityType, 'getFields', [
253 'action' => 'create',
254 'where' => $conditions,
255 'loadOptions' => $loadOptions,
256 'checkPermissions' => $this->checkPermissions,
257 ])->indexBy('name');
258 }
259 catch (NotImplementedException $e) {
260 return [];
261 }
262 }
263
264 }