a51b3ad1e4d07891ee15cc92014c382705bee4ba
[Packages/TYPO3.CMS.git] / typo3 / sysext / fluid / Classes / ViewHelpers / FormViewHelper.php
1 <?php
2 namespace TYPO3\CMS\Fluid\ViewHelpers;
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 /**
18 * Form view helper. Generates a <form> Tag.
19 *
20 * = Basic usage =
21 *
22 * Use <f:form> to output an HTML <form> tag which is targeted at the specified action, in the current controller and package.
23 * It will submit the form data via a POST request. If you want to change this, use method="get" as an argument.
24 * <code title="Example">
25 * <f:form action="...">...</f:form>
26 * </code>
27 *
28 * = A complex form with a specified encoding type =
29 *
30 * <code title="Form with enctype set">
31 * <f:form action=".." controller="..." package="..." enctype="multipart/form-data">...</f:form>
32 * </code>
33 *
34 * = A Form which should render a domain object =
35 *
36 * <code title="Binding a domain object to a form">
37 * <f:form action="..." name="customer" object="{customer}">
38 * <f:form.hidden property="id" />
39 * <f:form.textbox property="name" />
40 * </f:form>
41 * </code>
42 * This automatically inserts the value of {customer.name} inside the textbox and adjusts the name of the textbox accordingly.
43 */
44 class FormViewHelper extends \TYPO3\CMS\Fluid\ViewHelpers\Form\AbstractFormViewHelper
45 {
46 /**
47 * @var string
48 */
49 protected $tagName = 'form';
50
51 /**
52 * @var \TYPO3\CMS\Extbase\Security\Cryptography\HashService
53 */
54 protected $hashService;
55
56 /**
57 * @var \TYPO3\CMS\Extbase\Mvc\Controller\MvcPropertyMappingConfigurationService
58 */
59 protected $mvcPropertyMappingConfigurationService;
60
61 /**
62 * @var \TYPO3\CMS\Extbase\Service\ExtensionService
63 */
64 protected $extensionService;
65
66 /**
67 * We need the arguments of the formActionUri on requesthash calculation
68 * therefore we will store them in here right after calling uriBuilder
69 *
70 * @var array
71 */
72 protected $formActionUriArguments;
73
74 /**
75 * @param \TYPO3\CMS\Extbase\Security\Cryptography\HashService $hashService
76 */
77 public function injectHashService(\TYPO3\CMS\Extbase\Security\Cryptography\HashService $hashService)
78 {
79 $this->hashService = $hashService;
80 }
81
82 /**
83 * @param \TYPO3\CMS\Extbase\Mvc\Controller\MvcPropertyMappingConfigurationService $mvcPropertyMappingConfigurationService
84 */
85 public function injectMvcPropertyMappingConfigurationService(\TYPO3\CMS\Extbase\Mvc\Controller\MvcPropertyMappingConfigurationService $mvcPropertyMappingConfigurationService)
86 {
87 $this->mvcPropertyMappingConfigurationService = $mvcPropertyMappingConfigurationService;
88 }
89
90 /**
91 * @param \TYPO3\CMS\Extbase\Service\ExtensionService $extensionService
92 */
93 public function injectExtensionService(\TYPO3\CMS\Extbase\Service\ExtensionService $extensionService)
94 {
95 $this->extensionService = $extensionService;
96 }
97
98 /**
99 * Initialize arguments.
100 */
101 public function initializeArguments()
102 {
103 parent::initializeArguments();
104 $this->registerArgument('action', 'string', 'Target action');
105 $this->registerArgument('arguments', 'array', 'Arguments', false, []);
106 $this->registerArgument('controller', 'string', 'Target controller');
107 $this->registerArgument('extensionName', 'string', 'Target Extension Name (without "tx_" prefix and no underscores). If NULL the current extension name is used');
108 $this->registerArgument('pluginName', 'string', 'Target plugin. If empty, the current plugin name is used');
109 $this->registerArgument('pageUid', 'int', 'Target page uid');
110 $this->registerArgument('object', 'mixed', 'Object to use for the form. Use in conjunction with the "property" attribute on the sub tags');
111 $this->registerArgument('pageType', 'int', 'Target page type', false, 0);
112 $this->registerArgument('noCache', 'bool', 'set this to disable caching for the target page. You should not need this.', false, false);
113 $this->registerArgument('noCacheHash', 'bool', 'set this to suppress the cHash query parameter created by TypoLink. You should not need this.', false, false);
114 $this->registerArgument('section', 'string', 'The anchor to be added to the action URI (only active if $actionUri is not set)', false, '');
115 $this->registerArgument('format', 'string', 'The requested format (e.g. ".html") of the target page (only active if $actionUri is not set)', false, '');
116 $this->registerArgument('additionalParams', 'array', 'additional action URI query parameters that won\'t be prefixed like $arguments (overrule $arguments) (only active if $actionUri is not set)', false, []);
117 $this->registerArgument('absolute', 'bool', 'If set, an absolute action URI is rendered (only active if $actionUri is not set)', false, false);
118 $this->registerArgument('addQueryString', 'bool', 'If set, the current query parameters will be kept in the action URI (only active if $actionUri is not set)', false, false);
119 $this->registerArgument('argumentsToBeExcludedFromQueryString', 'array', 'arguments to be removed from the action URI. Only active if $addQueryString = TRUE and $actionUri is not set', false, []);
120 $this->registerArgument('addQueryStringMethod', 'string', 'Method to use when keeping query parameters (GET or POST, only active if $actionUri is not set', false, 'GET');
121 $this->registerArgument('fieldNamePrefix', 'string', 'Prefix that will be added to all field names within this form. If not set the prefix will be tx_yourExtension_plugin');
122 $this->registerArgument('actionUri', 'string', 'can be used to overwrite the "action" attribute of the form tag');
123 $this->registerArgument('objectName', 'string', 'name of the object that is bound to this form. If this argument is not specified, the name attribute of this form is used to determine the FormObjectName');
124 $this->registerArgument('hiddenFieldClassName', 'string', 'hiddenFieldClassName');
125 $this->registerTagAttribute('enctype', 'string', 'MIME type with which the form is submitted');
126 $this->registerTagAttribute('method', 'string', 'Transfer type (GET or POST)');
127 $this->registerTagAttribute('name', 'string', 'Name of form');
128 $this->registerTagAttribute('onreset', 'string', 'JavaScript: On reset of the form');
129 $this->registerTagAttribute('onsubmit', 'string', 'JavaScript: On submit of the form');
130 $this->registerTagAttribute('target', 'string', 'Target attribute of the form');
131 $this->registerTagAttribute('novalidate', 'bool', 'Indicate that the form is not to be validated on submit.');
132 $this->registerUniversalTagAttributes();
133 }
134
135 /**
136 * Render the form.
137 *
138 * @return string rendered form
139 */
140 public function render()
141 {
142 $this->setFormActionUri();
143 if (isset($this->arguments['method']) && strtolower($this->arguments['method']) === 'get') {
144 $this->tag->addAttribute('method', 'get');
145 } else {
146 $this->tag->addAttribute('method', 'post');
147 }
148
149 if (isset($this->arguments['novalidate']) && $this->arguments['novalidate'] === true) {
150 $this->tag->addAttribute('novalidate', 'novalidate');
151 }
152
153 $this->addFormObjectNameToViewHelperVariableContainer();
154 $this->addFormObjectToViewHelperVariableContainer();
155 $this->addFieldNamePrefixToViewHelperVariableContainer();
156 $this->addFormFieldNamesToViewHelperVariableContainer();
157 $formContent = $this->renderChildren();
158
159 if (isset($this->arguments['hiddenFieldClassName']) && $this->arguments['hiddenFieldClassName'] !== null) {
160 $content = LF . '<div class="' . htmlspecialchars($this->arguments['hiddenFieldClassName']) . '">';
161 } else {
162 $content = LF . '<div>';
163 }
164
165 $content .= $this->renderHiddenIdentityField($this->arguments['object'] ?? null, $this->getFormObjectName());
166 $content .= $this->renderAdditionalIdentityFields();
167 $content .= $this->renderHiddenReferrerFields();
168
169 // Render the trusted list of all properties after everything else has been rendered
170 $content .= $this->renderTrustedPropertiesField();
171
172 $content .= LF . '</div>' . LF;
173 $content .= $formContent;
174 $this->tag->setContent($content);
175 $this->removeFieldNamePrefixFromViewHelperVariableContainer();
176 $this->removeFormObjectFromViewHelperVariableContainer();
177 $this->removeFormObjectNameFromViewHelperVariableContainer();
178 $this->removeFormFieldNamesFromViewHelperVariableContainer();
179 $this->removeCheckboxFieldNamesFromViewHelperVariableContainer();
180 return $this->tag->render();
181 }
182
183 /**
184 * Sets the "action" attribute of the form tag
185 */
186 protected function setFormActionUri()
187 {
188 if ($this->hasArgument('actionUri')) {
189 $formActionUri = $this->arguments['actionUri'];
190 } else {
191 $pageUid = (isset($this->arguments['pageUid']) && (int)$this->arguments['pageUid'] > 0) ? (int)$this->arguments['pageUid'] : null;
192 $uriBuilder = $this->renderingContext->getControllerContext()->getUriBuilder();
193 $formActionUri = $uriBuilder
194 ->reset()
195 ->setTargetPageUid($pageUid)
196 ->setTargetPageType($this->arguments['pageType'] ?? 0)
197 ->setNoCache($this->arguments['noCache'] ?? false)
198 ->setUseCacheHash(isset($this->arguments['noCacheHash']) ? !$this->arguments['noCacheHash'] : true)
199 ->setSection($this->arguments['section'] ?? '')
200 ->setCreateAbsoluteUri($this->arguments['absolute'] ?? false)
201 ->setArguments(isset($this->arguments['additionalParams']) ? (array)$this->arguments['additionalParams'] : [])
202 ->setAddQueryString($this->arguments['addQueryString'] ?? false)
203 ->setAddQueryStringMethod($this->arguments['addQueryStringMethod'] ?? null)
204 ->setArgumentsToBeExcludedFromQueryString(isset($this->arguments['argumentsToBeExcludedFromQueryString']) ? (array)$this->arguments['argumentsToBeExcludedFromQueryString'] : [])
205 ->setFormat($this->arguments['format'] ?? '')
206 ->uriFor(
207 $this->arguments['action'] ?? null,
208 $this->arguments['arguments'] ?? [],
209 $this->arguments['controller'] ?? null,
210 $this->arguments['extensionName'] ?? null,
211 $this->arguments['pluginName'] ?? null
212 );
213 $this->formActionUriArguments = $uriBuilder->getArguments();
214 }
215 $this->tag->addAttribute('action', $formActionUri);
216 }
217
218 /**
219 * Render additional identity fields which were registered by form elements.
220 * This happens if a form field is defined like property="bla.blubb" - then we might need an identity property for the sub-object "bla".
221 *
222 * @return string HTML-string for the additional identity properties
223 */
224 protected function renderAdditionalIdentityFields()
225 {
226 if ($this->viewHelperVariableContainer->exists(\TYPO3\CMS\Fluid\ViewHelpers\FormViewHelper::class, 'additionalIdentityProperties')) {
227 $additionalIdentityProperties = $this->viewHelperVariableContainer->get(\TYPO3\CMS\Fluid\ViewHelpers\FormViewHelper::class, 'additionalIdentityProperties');
228 $output = '';
229 foreach ($additionalIdentityProperties as $identity) {
230 $output .= LF . $identity;
231 }
232 return $output;
233 }
234 return '';
235 }
236
237 /**
238 * Renders hidden form fields for referrer information about
239 * the current controller and action.
240 *
241 * @return string Hidden fields with referrer information
242 * @todo filter out referrer information that is equal to the target (e.g. same packageKey)
243 */
244 protected function renderHiddenReferrerFields()
245 {
246 $request = $this->renderingContext->getControllerContext()->getRequest();
247 $extensionName = $request->getControllerExtensionName();
248 $vendorName = $request->getControllerVendorName();
249 $controllerName = $request->getControllerName();
250 $actionName = $request->getControllerActionName();
251 $actionRequest = [
252 '@extension' => $extensionName,
253 '@controller' => $controllerName,
254 '@action' => $actionName,
255 ];
256
257 $result = LF;
258 $result .= '<input type="hidden" name="' . $this->prefixFieldName('__referrer[@extension]') . '" value="' . $extensionName . '" />' . LF;
259 if ($vendorName !== null) {
260 $result .= '<input type="hidden" name="' . $this->prefixFieldName('__referrer[@vendor]') . '" value="' . $vendorName . '" />' . LF;
261 $actionRequest['@vendor'] = $vendorName;
262 }
263 $result .= '<input type="hidden" name="' . $this->prefixFieldName('__referrer[@controller]') . '" value="' . $controllerName . '" />' . LF;
264 $result .= '<input type="hidden" name="' . $this->prefixFieldName('__referrer[@action]') . '" value="' . $actionName . '" />' . LF;
265 $result .= '<input type="hidden" name="' . $this->prefixFieldName('__referrer[arguments]') . '" value="' . htmlspecialchars($this->hashService->appendHmac(base64_encode(serialize($request->getArguments())))) . '" />' . LF;
266 $result .= '<input type="hidden" name="' . $this->prefixFieldName('__referrer[@request]') . '" value="' . htmlspecialchars($this->hashService->appendHmac(serialize($actionRequest))) . '" />' . LF;
267
268 return $result;
269 }
270
271 /**
272 * Adds the form object name to the ViewHelperVariableContainer if "objectName" argument or "name" attribute is specified.
273 */
274 protected function addFormObjectNameToViewHelperVariableContainer()
275 {
276 $formObjectName = $this->getFormObjectName();
277 if ($formObjectName !== null) {
278 $this->viewHelperVariableContainer->add(\TYPO3\CMS\Fluid\ViewHelpers\FormViewHelper::class, 'formObjectName', $formObjectName);
279 }
280 }
281
282 /**
283 * Removes the form name from the ViewHelperVariableContainer.
284 */
285 protected function removeFormObjectNameFromViewHelperVariableContainer()
286 {
287 $formObjectName = $this->getFormObjectName();
288 if ($formObjectName !== null) {
289 $this->viewHelperVariableContainer->remove(\TYPO3\CMS\Fluid\ViewHelpers\FormViewHelper::class, 'formObjectName');
290 }
291 }
292
293 /**
294 * Returns the name of the object that is bound to this form.
295 * If the "objectName" argument has been specified, this is returned. Otherwise the name attribute of this form.
296 * If neither objectName nor name arguments have been set, NULL is returned.
297 *
298 * @return string specified Form name or NULL if neither $objectName nor $name arguments have been specified
299 */
300 protected function getFormObjectName()
301 {
302 $formObjectName = null;
303 if ($this->hasArgument('objectName')) {
304 $formObjectName = $this->arguments['objectName'];
305 } elseif ($this->hasArgument('name')) {
306 $formObjectName = $this->arguments['name'];
307 }
308 return $formObjectName;
309 }
310
311 /**
312 * Adds the object that is bound to this form to the ViewHelperVariableContainer if the formObject attribute is specified.
313 */
314 protected function addFormObjectToViewHelperVariableContainer()
315 {
316 if ($this->hasArgument('object')) {
317 $this->viewHelperVariableContainer->add(\TYPO3\CMS\Fluid\ViewHelpers\FormViewHelper::class, 'formObject', $this->arguments['object']);
318 $this->viewHelperVariableContainer->add(\TYPO3\CMS\Fluid\ViewHelpers\FormViewHelper::class, 'additionalIdentityProperties', []);
319 }
320 }
321
322 /**
323 * Removes the form object from the ViewHelperVariableContainer.
324 */
325 protected function removeFormObjectFromViewHelperVariableContainer()
326 {
327 if ($this->hasArgument('object')) {
328 $this->viewHelperVariableContainer->remove(\TYPO3\CMS\Fluid\ViewHelpers\FormViewHelper::class, 'formObject');
329 $this->viewHelperVariableContainer->remove(\TYPO3\CMS\Fluid\ViewHelpers\FormViewHelper::class, 'additionalIdentityProperties');
330 }
331 }
332
333 /**
334 * Adds the field name prefix to the ViewHelperVariableContainer
335 */
336 protected function addFieldNamePrefixToViewHelperVariableContainer()
337 {
338 $fieldNamePrefix = $this->getFieldNamePrefix();
339 $this->viewHelperVariableContainer->add(\TYPO3\CMS\Fluid\ViewHelpers\FormViewHelper::class, 'fieldNamePrefix', $fieldNamePrefix);
340 }
341
342 /**
343 * Get the field name prefix
344 *
345 * @return string
346 */
347 protected function getFieldNamePrefix()
348 {
349 if ($this->hasArgument('fieldNamePrefix')) {
350 return $this->arguments['fieldNamePrefix'];
351 }
352 return $this->getDefaultFieldNamePrefix();
353 }
354
355 /**
356 * Removes field name prefix from the ViewHelperVariableContainer
357 */
358 protected function removeFieldNamePrefixFromViewHelperVariableContainer()
359 {
360 $this->viewHelperVariableContainer->remove(\TYPO3\CMS\Fluid\ViewHelpers\FormViewHelper::class, 'fieldNamePrefix');
361 }
362
363 /**
364 * Adds a container for form field names to the ViewHelperVariableContainer
365 */
366 protected function addFormFieldNamesToViewHelperVariableContainer()
367 {
368 $this->viewHelperVariableContainer->add(\TYPO3\CMS\Fluid\ViewHelpers\FormViewHelper::class, 'formFieldNames', []);
369 }
370
371 /**
372 * Removes the container for form field names from the ViewHelperVariableContainer
373 */
374 protected function removeFormFieldNamesFromViewHelperVariableContainer()
375 {
376 $this->viewHelperVariableContainer->remove(\TYPO3\CMS\Fluid\ViewHelpers\FormViewHelper::class, 'formFieldNames');
377 if ($this->viewHelperVariableContainer->exists(\TYPO3\CMS\Fluid\ViewHelpers\FormViewHelper::class, 'renderedHiddenFields')) {
378 $this->viewHelperVariableContainer->remove(\TYPO3\CMS\Fluid\ViewHelpers\FormViewHelper::class, 'renderedHiddenFields');
379 }
380 }
381
382 /**
383 * Render the request hash field
384 *
385 * @return string the hmac field
386 */
387 protected function renderRequestHashField()
388 {
389 $formFieldNames = $this->viewHelperVariableContainer->get(\TYPO3\CMS\Fluid\ViewHelpers\FormViewHelper::class, 'formFieldNames');
390 $this->postProcessUriArgumentsForRequestHash($this->formActionUriArguments, $formFieldNames);
391 $requestHash = $this->requestHashService->generateRequestHash($formFieldNames, $this->getFieldNamePrefix());
392 return '<input type="hidden" name="' . $this->prefixFieldName('__hmac') . '" value="' . htmlspecialchars($requestHash) . '" />';
393 }
394
395 /**
396 * Add the URI arguments after postprocessing to the request hash as well.
397 */
398 protected function postProcessUriArgumentsForRequestHash($arguments, &$results, $currentPrefix = '', $level = 0)
399 {
400 if (count($arguments)) {
401 foreach ($arguments as $argumentName => $argumentValue) {
402 if (is_array($argumentValue)) {
403 $prefix = $level == 0 ? $argumentName : $currentPrefix . '[' . $argumentName . ']';
404 $this->postProcessUriArgumentsForRequestHash($argumentValue, $results, $prefix, $level + 1);
405 } else {
406 $results[] = $level == 0 ? $argumentName : $currentPrefix . '[' . $argumentName . ']';
407 }
408 }
409 }
410 }
411
412 /**
413 * Retrieves the default field name prefix for this form
414 *
415 * @return string default field name prefix
416 */
417 protected function getDefaultFieldNamePrefix()
418 {
419 $request = $this->renderingContext->getControllerContext()->getRequest();
420 if ($this->hasArgument('extensionName')) {
421 $extensionName = $this->arguments['extensionName'];
422 } else {
423 $extensionName = $request->getControllerExtensionName();
424 }
425 if ($this->hasArgument('pluginName')) {
426 $pluginName = $this->arguments['pluginName'];
427 } else {
428 $pluginName = $request->getPluginName();
429 }
430 if ($extensionName !== null && $pluginName != null) {
431 return $this->extensionService->getPluginNamespace($extensionName, $pluginName);
432 }
433 return '';
434 }
435
436 /**
437 * Remove Checkbox field names from ViewHelper variable container, to start from scratch when a new form starts.
438 */
439 protected function removeCheckboxFieldNamesFromViewHelperVariableContainer()
440 {
441 if ($this->viewHelperVariableContainer->exists(\TYPO3\CMS\Fluid\ViewHelpers\Form\CheckboxViewHelper::class, 'checkboxFieldNames')) {
442 $this->viewHelperVariableContainer->remove(\TYPO3\CMS\Fluid\ViewHelpers\Form\CheckboxViewHelper::class, 'checkboxFieldNames');
443 }
444 }
445
446 /**
447 * Render the request hash field
448 *
449 * @return string The hmac field
450 */
451 protected function renderTrustedPropertiesField()
452 {
453 $formFieldNames = $this->viewHelperVariableContainer->get(\TYPO3\CMS\Fluid\ViewHelpers\FormViewHelper::class, 'formFieldNames');
454 $requestHash = $this->mvcPropertyMappingConfigurationService->generateTrustedPropertiesToken($formFieldNames, $this->getFieldNamePrefix());
455 return '<input type="hidden" name="' . $this->prefixFieldName('__trustedProperties') . '" value="' . htmlspecialchars($requestHash) . '" />';
456 }
457 }