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