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