ImageManipulationElement.php 9.11 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
namespace TYPO3\CMS\Backend\Form\Element;

/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

use TYPO3\CMS\Backend\Form\FormEngine;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException;
use TYPO3\CMS\Core\Resource\File;
use TYPO3\CMS\Core\Resource\ResourceFactory;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
use TYPO3\CMS\Extbase\Utility\ArrayUtility;
25
use TYPO3\CMS\Backend\Form\NodeFactory;
26
27

/**
Christian Kuhn's avatar
Christian Kuhn committed
28
 * Generation of image manipulation TCEform element
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
 */
class ImageManipulationElement extends AbstractFormElement {

	/**
	 * Default element configuration
	 *
	 * @var array
	 */
	protected $defaultConfig = array(
		'file_field' => 'uid_local',
		'enableZoom' => FALSE,
		'allowedExtensions' => NULL, // default: $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext']
		'ratios' => array(
			'1.7777777777777777' => 'LLL:EXT:lang/locallang_wizards.xlf:imwizard.ratio.16_9',
			'1.3333333333333333' => 'LLL:EXT:lang/locallang_wizards.xlf:imwizard.ratio.4_3',
			'1' => 'LLL:EXT:lang/locallang_wizards.xlf:imwizard.ratio.1_1',
			'NaN' => 'LLL:EXT:lang/locallang_wizards.xlf:imwizard.ratio.free',
		)
	);

	/**
	 * Handler for unknown types.
	 *
Christian Kuhn's avatar
Christian Kuhn committed
52
	 * @return array As defined in initializeResultArray() of AbstractNode
53
	 */
Christian Kuhn's avatar
Christian Kuhn committed
54
55
56
57
58
59
	public function render() {
		$languageService = $this->getLanguageService();

		$row = $this->globalOptions['databaseRow'];
		$parameterArray = $this->globalOptions['parameterArray'];

60
		// If ratios are set do not add default options
Christian Kuhn's avatar
Christian Kuhn committed
61
		if (isset($parameterArray['fieldConf']['config']['ratios'])) {
62
63
			unset($this->defaultConfig['ratios']);
		}
Christian Kuhn's avatar
Christian Kuhn committed
64
		$config = ArrayUtility::arrayMergeRecursiveOverrule($this->defaultConfig, $parameterArray['fieldConf']['config']);
65
66
67
68
69
70
71

		// By default we allow all image extensions that can be handled by the GFX functionality
		if ($config['allowedExtensions'] === NULL) {
			$config['allowedExtensions'] = $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'];
		}

		if ($this->isGlobalReadonly() || $config['readOnly']) {
72
73
			$options = array();
			$options['parameterArray'] = array(
74
75
76
				'fieldConf' => array(
					'config' => $config,
				),
Christian Kuhn's avatar
Christian Kuhn committed
77
				'itemFormElValue' => $parameterArray['itemFormElValue'],
78
			);
79
			$options['renderType'] = 'none';
80
81
82
			/** @var NodeFactory $nodeFactory */
			$nodeFactory = $this->globalOptions['nodeFactory'];
			return $nodeFactory->create($options)->render();
83
84
85
86
87
88
89
90
91
92
93
94
		}

		$file = $this->getFile($row, $config['file_field']);
		if (!$file) {
			return '';
		}

		$content = '';
		$preview = '';
		if (GeneralUtility::inList(mb_strtolower($config['allowedExtensions']), mb_strtolower($file->getExtension()))) {

			// Get preview
Christian Kuhn's avatar
Christian Kuhn committed
95
			$preview = $this->getPreview($file, $parameterArray['itemFormElValue']);
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128

			// Check if ratio labels hold translation strings
			foreach ((array)$config['ratios'] as $ratio => $label) {
				$config['ratios'][$ratio] = $languageService->sL($label, TRUE);
			}

			$formFieldId = str_replace('.', '', uniqid('formengine-image-manipulation-', TRUE));
			$wizardData = array(
				'file' => $file->getUid(),
				'zoom' => $config['enableZoom'] ? '1' : '0',
				'ratios' => json_encode($config['ratios']),
			);
			$wizardData['token'] = GeneralUtility::hmac(implode('|', $wizardData), 'ImageManipulationWizard');

			$buttonAttributes = array(
				'data-url' => BackendUtility::getAjaxUrl('ImageManipulationWizard::getHtmlForImageManipulationWizard', $wizardData),
				'data-severity' => 'notice',
				'data-image-name' => $file->getNameWithoutExtension(),
				'data-image-uid' => $file->getUid(),
				'data-file-field' => $config['file_field'],
				'data-field' => $formFieldId,
			);

			$button = '<button class="btn btn-default t3js-image-manipulation-trigger"';
			foreach ($buttonAttributes as $key => $value) {
				$button .= ' ' . $key . '="' . htmlspecialchars($value) . '"';
			}
			$button .= '><span class="t3-icon fa fa-crop"></span>';
			$button .= $languageService->sL('LLL:EXT:lang/locallang_wizards.xlf:imwizard.open-editor', TRUE);
			$button .= '</button>';

			$inputField = '<input type="hidden" '
				. 'id="' . $formFieldId . '" '
Christian Kuhn's avatar
Christian Kuhn committed
129
130
				. 'name="' . $parameterArray['itemFormElName'] . '" '
				. 'value="' . htmlspecialchars($parameterArray['itemFormElValue']) . '" />';
131
132
133

			$content .= $inputField . $button;

Christian Kuhn's avatar
Christian Kuhn committed
134
			$content .= $this->getImageManipulationInfoTable($parameterArray['itemFormElValue']);
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152

			/** @var $pageRenderer \TYPO3\CMS\Core\Page\PageRenderer */
			$pageRenderer = $GLOBALS['SOBE']->doc->getPageRenderer();
			$pageRenderer->loadRequireJsModule(
				'TYPO3/CMS/Backend/ImageManipulation',
				'function(ImageManipulation){ImageManipulation.initializeTrigger()}' // Initialize after load
			);
		}

		$content .= '<p class="text-muted"><em>' . $languageService->sL('LLL:EXT:lang/locallang_wizards.xlf:imwizard.supported-types-message', TRUE) . '<br />';
		$content .= mb_strtoupper(implode(', ', GeneralUtility::trimExplode(',', $config['allowedExtensions'])));
		$content .= '</em></p>';

		$item = '<div class="media">';
		$item .= $preview;
		$item .= '<div class="media-body">' . $content . '</div>';
		$item .= '</div>';

Christian Kuhn's avatar
Christian Kuhn committed
153
154
155
		$resultArray = $this->initializeResultArray();
		$resultArray['html'] = $item;
		return $resultArray;
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
	}

	/**
	 * Get file object
	 *
	 * @param array $row
	 * @param string $fieldName
	 * @return NULL|\TYPO3\CMS\Core\Resource\File
	 */
	protected function getFile(array $row, $fieldName) {
		$file = NULL;
		$fileUid = !empty($row[$fieldName]) ? $row[$fieldName] : NULL;

		if (strpos($fileUid, 'sys_file_') === 0) {
			$fileUid = substr($fileUid, 9);
		}
		if (MathUtility::canBeInterpretedAsInteger($fileUid)) {
			try {
				$file = ResourceFactory::getInstance()->getFileObject($fileUid);
			} catch (FileDoesNotExistException $e) {
			}
		}
		return $file;
	}

	/**
	 * Get preview image if cropping is set
	 *
	 * @param File $file
	 * @param string $crop
	 * @return string
	 */
	public function getPreview(File $file, $crop) {
189
190
191
		$thumbnail = '';
		$maxWidth = 150;
		$maxHeight = 200;
192
		if ($crop) {
193
			$imageSetup = array('maxWidth' => $maxWidth, 'maxHeight' => $maxHeight, 'crop' => $crop);
194
195
196
197
			$processedImage = $file->process(\TYPO3\CMS\Core\Resource\ProcessedFile::CONTEXT_IMAGECROPSCALEMASK, $imageSetup);
			// Only use a thumbnail if the processing process was successful by checking if image width is set
			if ($processedImage->getProperty('width')) {
				$imageUrl = $processedImage->getPublicUrl(TRUE);
198
199
				$thumbnail = '<img src="' . $imageUrl . '" ' .
					'class="thumbnail thumbnail-status" ' .
200
201
202
203
					'width="' . $processedImage->getProperty('width') . '" ' .
					'height="' . $processedImage->getProperty('height') . '" >';
			}
		}
204
205
206
207
208
209
210
211
212

		$preview = '<div class="media-left">';
		$preview .= '<div class="t3js-image-manipulation-preview media-object' . ($thumbnail ? '' : ' hide'). '" ';
		// Set preview width/height needed by cropper
		$preview .= 'data-preview-width="' . $maxWidth . '" data-preview-height="' . $maxHeight . '">';
		$preview .= $thumbnail;
		$preview .= '</div></div>';

		return $preview;
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
	}

	/**
	 * Get image manipulation info table
	 *
	 * @param string $rawImageManipulationValue
	 * @return string
	 */
	protected function getImageManipulationInfoTable($rawImageManipulationValue) {
		$content = '';
		$imageManipulation = NULL;
		$x = $y = $width = $height = 0;

		// Determine cropping values
		if ($rawImageManipulationValue) {
			$imageManipulation = json_decode($rawImageManipulationValue);
			if (is_object($imageManipulation)) {
				$x = (int)$imageManipulation->x;
				$y = (int)$imageManipulation->y;
				$width = (int)$imageManipulation->width;
				$height = (int)$imageManipulation->height;
			} else {
				$imageManipulation = NULL;
			}
		}
		$languageService = $this->getLanguageService();

		$content .= '<div class="table-fit-block table-spacer-wrap">';
		$content .= '<table class="table table-no-borders t3js-image-manipulation-info'. ($imageManipulation === NULL ? ' hide' : '') . '">';
		$content .= '<tr><td>' . $languageService->sL('LLL:EXT:lang/locallang_wizards.xlf:imwizard.crop-x', TRUE) . '</td>';
		$content .= '<td class="t3js-image-manipulation-info-crop-x">' . $x . 'px</td></tr>';
		$content .= '<tr><td>' . $languageService->sL('LLL:EXT:lang/locallang_wizards.xlf:imwizard.crop-y', TRUE) . '</td>';
		$content .= '<td class="t3js-image-manipulation-info-crop-y">' . $y . 'px</td></tr>';
		$content .= '<tr><td>' . $languageService->sL('LLL:EXT:lang/locallang_wizards.xlf:imwizard.crop-width', TRUE) . '</td>';
		$content .= '<td class="t3js-image-manipulation-info-crop-width">' . $width . 'px</td></tr>';
		$content .= '<tr><td>' . $languageService->sL('LLL:EXT:lang/locallang_wizards.xlf:imwizard.crop-height', TRUE) . '</td>';
		$content .= '<td class="t3js-image-manipulation-info-crop-height">' . $height . 'px</td></tr>';
		$content .= '</table>';
		$content .= '</div>';

		return $content;
	}
}