e0e5b0798633a2ce7457dc9cb449269aee027861
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Form / InlineStackProcessor.php
1 <?php
2 namespace TYPO3\CMS\Backend\Form;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Form\Utility\FormEngineUtility;
18 use TYPO3\CMS\Backend\Utility\BackendUtility;
19 use TYPO3\CMS\Core\Utility\GeneralUtility;
20
21 /**
22 * Handle inline stack.
23 *
24 * Code related to inline elements need to know their nesting level. This class takes
25 * care of the according handling and can return field prefixes to be used in DOM.
26 *
27 * @internal: This class may change any time or vanish altogether
28 */
29 class InlineStackProcessor
30 {
31 /**
32 * The structure/hierarchy where working in, e.g. cascading inline tables
33 *
34 * @var array
35 */
36 protected $inlineStructure = [];
37
38 /**
39 * One of two possible initialize methods setting a given structure.
40 *
41 * @param array $structure
42 */
43 public function initializeByGivenStructure(array $structure = [])
44 {
45 $this->inlineStructure = $structure;
46 }
47
48 /**
49 * Convert the DOM object-id of an inline container to an array.
50 * The object-id could look like 'data-parentPageId-tx_mmftest_company-1-employees'.
51 * This initializes $this->inlineStructure - used by AJAX entry points
52 * There are two keys:
53 * - 'stable': Containing full qualified identifiers (table, uid and field)
54 * - 'unstable': Containing partly filled data (e.g. only table and possibly field)
55 *
56 * @param string $domObjectId The DOM object-id
57 */
58 public function initializeByParsingDomObjectIdString($domObjectId)
59 {
60 $unstable = [];
61 $vector = ['table', 'uid', 'field'];
62
63 // Substitute FlexForm addition and make parsing a bit easier
64 $domObjectId = str_replace('---', ':', $domObjectId);
65 // The starting pattern of an object identifier (e.g. "data-<firstPidValue>-<anything>)
66 $pattern = '/^data' . '-' . '(.+?)' . '-' . '(.+)$/';
67
68 if (preg_match($pattern, $domObjectId, $match)) {
69 $inlineFirstPid = $match[1];
70 $parts = explode('-', $match[2]);
71 $partsCnt = count($parts);
72 for ($i = 0; $i < $partsCnt; $i++) {
73 if ($i > 0 && $i % 3 == 0) {
74 // Load the TCA configuration of the table field and store it in the stack
75 // @todo: This TCA loading here must fall - config sub-array shouldn't exist at all!
76 $unstable['config'] = $GLOBALS['TCA'][$unstable['table']]['columns'][$unstable['field']]['config'];
77 // Fetch TSconfig:
78 // @todo: aaargs ;)
79 $TSconfig = FormEngineUtility::getTSconfigForTableRow($unstable['table'], ['uid' => $unstable['uid'], 'pid' => $inlineFirstPid], $unstable['field']);
80 // Override TCA field config by TSconfig:
81 if (!$TSconfig['disabled']) {
82 $unstable['config'] = FormEngineUtility::overrideFieldConf($unstable['config'], $TSconfig);
83 }
84 $unstable['localizationMode'] = BackendUtility::getInlineLocalizationMode($unstable['table'], $unstable['config']);
85
86 // Extract FlexForm from field part (if any)
87 if (strpos($unstable['field'], ':') !== false) {
88 $fieldParts = GeneralUtility::trimExplode(':', $unstable['field']);
89 $unstable['field'] = array_shift($fieldParts);
90 // FlexForm parts start with data:
91 if (!empty($fieldParts) && $fieldParts[0] === 'data') {
92 $unstable['flexform'] = $fieldParts;
93 }
94 }
95
96 $this->inlineStructure['stable'][] = $unstable;
97 $unstable = [];
98 }
99 $unstable[$vector[$i % 3]] = $parts[$i];
100 }
101 if (!empty($unstable)) {
102 $this->inlineStructure['unstable'] = $unstable;
103 }
104 }
105 }
106
107 /**
108 * Injects configuration via AJAX calls.
109 * This is used by inline ajax calls that transfer configuration options back to the stack for initialization
110 *
111 * @param array $config Given config extracted from ajax call
112 * @todo: Review this construct - Why can't the ajax call fetch these data on its own and transfers it to client instead?
113 */
114 public function injectAjaxConfiguration(array $config)
115 {
116 $level = $this->calculateStructureLevel(-1);
117 if (empty($config) || $level === false) {
118 return;
119 }
120 $current = &$this->inlineStructure['stable'][$level];
121 $current['config'] = $config;
122 $current['localizationMode'] = BackendUtility::getInlineLocalizationMode(
123 $current['table'],
124 $current['config']
125 );
126 }
127
128 /**
129 * Get current structure stack
130 *
131 * @return array Current structure stack
132 */
133 public function getStructure()
134 {
135 return $this->inlineStructure;
136 }
137
138 /**
139 * Add a stable structure to the stack
140 *
141 * @param array $structureItem
142 */
143 public function pushStableStructureItem(array $structureItem = [])
144 {
145 $this->inlineStructure['stable'][] = $structureItem;
146 }
147
148 /**
149 * Prefix for inline form fields
150 *
151 * @return string
152 */
153 public function getCurrentStructureFormPrefix()
154 {
155 $current = $this->getStructureLevel(-1);
156 $inlineFormName = '';
157 // If there are still more inline levels available
158 if ($current !== false) {
159 $inlineFormName = 'data' . $this->getStructureItemName($current, 'Disposal_AttributeName');
160 }
161 return $inlineFormName;
162 }
163
164 /**
165 * DOM object-id for this inline level
166 *
167 * @param int $inlineFirstPid Pid of top level inline element storage
168 * @return string
169 */
170 public function getCurrentStructureDomObjectIdPrefix($inlineFirstPid)
171 {
172 $current = $this->getStructureLevel(-1);
173 $inlineDomObjectId = '';
174 // If there are still more inline levels available
175 if ($current !== false) {
176 $inlineDomObjectId = 'data' . '-' . $inlineFirstPid . '-' . $this->getStructurePath();
177 }
178 return $inlineDomObjectId;
179 }
180
181 /**
182 * Get a level from the stack and return the data.
183 * If the $level value is negative, this function works top-down,
184 * if the $level value is positive, this function works bottom-up.
185 * Hint: If -1 is given, the "current" - most bottom "stable" item is returned
186 *
187 * @param int $level Which level to return
188 * @return array The item of the stack at the requested level
189 */
190 public function getStructureLevel($level)
191 {
192 $level = $this->calculateStructureLevel($level);
193
194 if ($level !== false) {
195 return $this->inlineStructure['stable'][$level];
196 } else {
197 return false;
198 }
199 }
200
201 /**
202 * Get the "unstable" structure item from structure stack.
203 * This is typically initialized by initializeByParsingDomObjectIdString()
204 *
205 * @return array Unstable structure item
206 * @throws \RuntimeException
207 */
208 public function getUnstableStructure()
209 {
210 if (!isset($this->inlineStructure['unstable'])) {
211 throw new \RuntimeException('No unstable inline structure found', 1428582655);
212 }
213 return $this->inlineStructure['unstable'];
214 }
215
216 /**
217 * Calculates structure level.
218 *
219 * @param int $level Which level to return
220 * @return bool|int
221 */
222 protected function calculateStructureLevel($level)
223 {
224 $result = false;
225 $inlineStructureCount = count($this->inlineStructure['stable']);
226 if ($level < 0) {
227 $level = $inlineStructureCount + $level;
228 }
229 if ($level >= 0 && $level < $inlineStructureCount) {
230 $result = $level;
231 }
232 return $result;
233 }
234
235 /**
236 * Get the identifiers of a given depth of level, from the top of the stack to the bottom.
237 * An identifier looks like "<table>-<uid>-<field>".
238 *
239 * @param int $structureDepth How much levels to output, beginning from the top of the stack
240 * @return string The path of identifiers
241 */
242 protected function getStructurePath($structureDepth = -1)
243 {
244 $structureLevels = [];
245 $structureCount = $this->getStructureDepth();
246 if ($structureDepth < 0 || $structureDepth > $structureCount) {
247 $structureDepth = $structureCount;
248 }
249 for ($i = 1; $i <= $structureDepth; $i++) {
250 array_unshift($structureLevels, $this->getStructureItemName($this->getStructureLevel(-$i), 'Disposal_AttributeId'));
251 }
252 return implode('-', $structureLevels);
253 }
254
255 /**
256 * Get the depth of the stable structure stack.
257 * (count($this->inlineStructure['stable'])
258 *
259 * @return int The depth of the structure stack
260 */
261 public function getStructureDepth()
262 {
263 return count($this->inlineStructure['stable']);
264 }
265
266 /**
267 * Create a name/id for usage in HTML output of a level of the structure stack to be used in form names.
268 *
269 * @param array $levelData Array of a level of the structure stack (containing the keys table, uid and field)
270 * @param string $disposal How the structure name is used (e.g. as <div id="..."> or <input name="..." />)
271 * @return string The name/id of that level, to be used for HTML output
272 */
273 protected function getStructureItemName($levelData, $disposal = 'Disposal_AttributeId')
274 {
275 $name = null;
276
277 if (is_array($levelData)) {
278 $parts = [$levelData['table'], $levelData['uid']];
279
280 if (!empty($levelData['field'])) {
281 $parts[] = $levelData['field'];
282 }
283
284 // Use in name attributes:
285 if ($disposal === 'Disposal_AttributeName') {
286 if (!empty($levelData['field']) && !empty($levelData['flexform']) && $this->getStructureLevel(-1) === $levelData) {
287 $parts[] = implode('][', $levelData['flexform']);
288 }
289 $name = '[' . implode('][', $parts) . ']';
290 // Use in object id attributes:
291 } else {
292 $name = implode('-', $parts);
293
294 if (!empty($levelData['field']) && !empty($levelData['flexform'])) {
295 array_unshift($levelData['flexform'], $name);
296 $name = implode('---', $levelData['flexform']);
297 }
298 }
299 }
300
301 return $name;
302 }
303 }