Completed
Push — master ( fb6736...59da86 )
by Fabien
03:11 queued 01:31
created
Classes/ViewHelpers/Form/Select/StorageViewHelper.php 1 patch
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -20,50 +20,50 @@
 block discarded – undo
20 20
 class StorageViewHelper extends AbstractViewHelper
21 21
 {
22 22
 
23
-    /**
24
-     * @return void
25
-     */
26
-    public function initializeArguments()
27
-    {
28
-        $this->registerArgument('objects', 'array', '', false, []);
29
-    }
23
+	/**
24
+	 * @return void
25
+	 */
26
+	public function initializeArguments()
27
+	{
28
+		$this->registerArgument('objects', 'array', '', false, []);
29
+	}
30 30
 
31
-    /**
32
-     * Render a file upload field
33
-     *
34
-     * @return string
35
-     */
36
-    public function render()
37
-    {
38
-        $objects = $this->arguments['objects'];
31
+	/**
32
+	 * Render a file upload field
33
+	 *
34
+	 * @return string
35
+	 */
36
+	public function render()
37
+	{
38
+		$objects = $this->arguments['objects'];
39 39
 
40
-        // Check if a storages is selected
41
-        $currentStorage = $this->getMediaModule()->getCurrentStorage();
40
+		// Check if a storages is selected
41
+		$currentStorage = $this->getMediaModule()->getCurrentStorage();
42 42
 
43
-        $template = '<select name="%s[target]">%s</select>';
44
-        $options = [];
45
-        foreach ($objects as $storage) {
43
+		$template = '<select name="%s[target]">%s</select>';
44
+		$options = [];
45
+		foreach ($objects as $storage) {
46 46
 
47
-            /** @var \TYPO3\CMS\Core\Resource\ResourceStorage $storage */
48
-            $options[] = sprintf('<option value="%s" %s>%s %s</option>',
49
-                $storage->getUid(),
50
-                is_object($currentStorage) && $currentStorage->getUid() == $storage->getUid() ? 'selected="selected"' : '',
51
-                $storage->getName(),
52
-                !$storage->isOnline() ? '(offline)' : ''
53
-            );
54
-        }
55
-        return sprintf($template,
56
-            VidiModule::getParameterPrefix(),
57
-            implode("\n", $options)
58
-        );
59
-    }
47
+			/** @var \TYPO3\CMS\Core\Resource\ResourceStorage $storage */
48
+			$options[] = sprintf('<option value="%s" %s>%s %s</option>',
49
+				$storage->getUid(),
50
+				is_object($currentStorage) && $currentStorage->getUid() == $storage->getUid() ? 'selected="selected"' : '',
51
+				$storage->getName(),
52
+				!$storage->isOnline() ? '(offline)' : ''
53
+			);
54
+		}
55
+		return sprintf($template,
56
+			VidiModule::getParameterPrefix(),
57
+			implode("\n", $options)
58
+		);
59
+	}
60 60
 
61
-    /**
62
-     * @return MediaModule|object
63
-     */
64
-    protected function getMediaModule()
65
-    {
66
-        return GeneralUtility::makeInstance(\Fab\Media\Module\MediaModule::class);
67
-    }
61
+	/**
62
+	 * @return MediaModule|object
63
+	 */
64
+	protected function getMediaModule()
65
+	{
66
+		return GeneralUtility::makeInstance(\Fab\Media\Module\MediaModule::class);
67
+	}
68 68
 
69 69
 }
Please login to merge, or discard this patch.
Classes/ViewHelpers/ImageDimensionViewHelper.php 1 patch
Indentation   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -17,31 +17,31 @@
 block discarded – undo
17 17
 class ImageDimensionViewHelper extends AbstractViewHelper
18 18
 {
19 19
 
20
-    /**
21
-     * @return void
22
-     */
23
-    public function initializeArguments()
24
-    {
25
-        $this->registerArgument('preset', 'string', '', true);
26
-        $this->registerArgument('dimension', 'string', '', false, 'width');
27
-    }
20
+	/**
21
+	 * @return void
22
+	 */
23
+	public function initializeArguments()
24
+	{
25
+		$this->registerArgument('preset', 'string', '', true);
26
+		$this->registerArgument('dimension', 'string', '', false, 'width');
27
+	}
28 28
 
29
-    /**
30
-     * Returns preset values related to an image dimension
31
-     *
32
-     * @return int
33
-     */
34
-    public function render()
35
-    {
36
-        $preset = $this->arguments['preset'];
37
-        $dimension = $this->arguments['dimension'];
29
+	/**
30
+	 * Returns preset values related to an image dimension
31
+	 *
32
+	 * @return int
33
+	 */
34
+	public function render()
35
+	{
36
+		$preset = $this->arguments['preset'];
37
+		$dimension = $this->arguments['dimension'];
38 38
 
39
-        $imageDimension = ImagePresetUtility::getInstance()->preset($preset);
40
-        if ($dimension === 'width') {
41
-            $result = $imageDimension->getWidth();
42
-        } else {
43
-            $result = $imageDimension->getHeight();
44
-        }
45
-        return $result;
46
-    }
39
+		$imageDimension = ImagePresetUtility::getInstance()->preset($preset);
40
+		if ($dimension === 'width') {
41
+			$result = $imageDimension->getWidth();
42
+		} else {
43
+			$result = $imageDimension->getHeight();
44
+		}
45
+		return $result;
46
+	}
47 47
 }
Please login to merge, or discard this patch.
Classes/Module/VidiModule.php 1 patch
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -16,33 +16,33 @@
 block discarded – undo
16 16
 class VidiModule
17 17
 {
18 18
 
19
-    const SIGNATURE = 'file_VidiSysFileM1';
20
-    const PARAMETER_PREFIX = 'tx_vidi_file_vidisysfilem1';
21
-
22
-    const SIGNATURE_FOLDER_TREE_OMITTED = 'content_VidiSysFileM1';
23
-    const PARAMETER_PREFIX_FOLDER_TREE_OMITTED = 'tx_vidi_content_vidisysfilem1';
24
-
25
-    /**
26
-     * @return string
27
-     */
28
-    static public function getSignature()
29
-    {
30
-        return self::getMediaModule()->hasFolderTree() ? self::SIGNATURE : self::SIGNATURE_FOLDER_TREE_OMITTED;
31
-    }
32
-
33
-    /**
34
-     * @return string
35
-     */
36
-    static public function getParameterPrefix()
37
-    {
38
-        return self::getMediaModule()->hasFolderTree() ? self::PARAMETER_PREFIX : self::PARAMETER_PREFIX_FOLDER_TREE_OMITTED;
39
-    }
40
-
41
-    /**
42
-     * @return MediaModule|object
43
-     */
44
-    static protected function getMediaModule()
45
-    {
46
-        return GeneralUtility::makeInstance(\Fab\Media\Module\MediaModule::class);
47
-    }
19
+	const SIGNATURE = 'file_VidiSysFileM1';
20
+	const PARAMETER_PREFIX = 'tx_vidi_file_vidisysfilem1';
21
+
22
+	const SIGNATURE_FOLDER_TREE_OMITTED = 'content_VidiSysFileM1';
23
+	const PARAMETER_PREFIX_FOLDER_TREE_OMITTED = 'tx_vidi_content_vidisysfilem1';
24
+
25
+	/**
26
+	 * @return string
27
+	 */
28
+	static public function getSignature()
29
+	{
30
+		return self::getMediaModule()->hasFolderTree() ? self::SIGNATURE : self::SIGNATURE_FOLDER_TREE_OMITTED;
31
+	}
32
+
33
+	/**
34
+	 * @return string
35
+	 */
36
+	static public function getParameterPrefix()
37
+	{
38
+		return self::getMediaModule()->hasFolderTree() ? self::PARAMETER_PREFIX : self::PARAMETER_PREFIX_FOLDER_TREE_OMITTED;
39
+	}
40
+
41
+	/**
42
+	 * @return MediaModule|object
43
+	 */
44
+	static protected function getMediaModule()
45
+	{
46
+		return GeneralUtility::makeInstance(\Fab\Media\Module\MediaModule::class);
47
+	}
48 48
 }
49 49
\ No newline at end of file
Please login to merge, or discard this patch.
Classes/Backend/TceForms.php 1 patch
Indentation   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -20,36 +20,36 @@
 block discarded – undo
20 20
 class TceForms extends AbstractFormElement
21 21
 {
22 22
 
23
-    /**
24
-     * @return array
25
-     */
26
-    public function render()
27
-    {
28
-        // Load StyleSheets in the Page Renderer
29
-        $pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
30
-        $cssFile = ExtensionManagementUtility::extPath('media') . 'Resources/Public/StyleSheets/fineuploader.tce.css';
31
-        $pageRenderer->addCssFile($cssFile);
32
-
33
-        // language labels for JavaScript files
34
-        $pageRenderer->addInlineLanguageLabelFile(ExtensionManagementUtility::extPath('media') . 'Resources/Private/Language/locallang.xlf', 'media_file_upload');
35
-
36
-        // js files to be loaded
37
-        $pageRenderer->addJsFile(ExtensionManagementUtility::extPath('media') . 'Resources/Public/JavaScript/Encoder.js');
38
-        $pageRenderer->addJsFile(ExtensionManagementUtility::extPath('media') . 'Resources/Public/Libraries/Fineuploader/jquery.fineuploader-5.0.9.min.js');
39
-
40
-        $result = $this->initializeResultArray();
41
-
42
-        $fileMetadataRecord = $this->data['databaseRow'];
43
-
44
-        if ($fileMetadataRecord['file'] <= 0) {
45
-            throw new \Exception('I could not find a valid file identifier', 1392926871);
46
-        }
47
-
48
-        /** @var $fileUpload \Fab\Media\Form\FileUploadTceForms */
49
-        $fileUpload = GeneralUtility::makeInstance(\Fab\Media\Form\FileUploadTceForms::class);
50
-        $fileUpload->setValue($fileMetadataRecord['file'][0])->setPrefix(MediaModule::getParameterPrefix());
51
-        $result['html'] = $fileUpload->render();
52
-        return $result;
53
-    }
23
+	/**
24
+	 * @return array
25
+	 */
26
+	public function render()
27
+	{
28
+		// Load StyleSheets in the Page Renderer
29
+		$pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
30
+		$cssFile = ExtensionManagementUtility::extPath('media') . 'Resources/Public/StyleSheets/fineuploader.tce.css';
31
+		$pageRenderer->addCssFile($cssFile);
32
+
33
+		// language labels for JavaScript files
34
+		$pageRenderer->addInlineLanguageLabelFile(ExtensionManagementUtility::extPath('media') . 'Resources/Private/Language/locallang.xlf', 'media_file_upload');
35
+
36
+		// js files to be loaded
37
+		$pageRenderer->addJsFile(ExtensionManagementUtility::extPath('media') . 'Resources/Public/JavaScript/Encoder.js');
38
+		$pageRenderer->addJsFile(ExtensionManagementUtility::extPath('media') . 'Resources/Public/Libraries/Fineuploader/jquery.fineuploader-5.0.9.min.js');
39
+
40
+		$result = $this->initializeResultArray();
41
+
42
+		$fileMetadataRecord = $this->data['databaseRow'];
43
+
44
+		if ($fileMetadataRecord['file'] <= 0) {
45
+			throw new \Exception('I could not find a valid file identifier', 1392926871);
46
+		}
47
+
48
+		/** @var $fileUpload \Fab\Media\Form\FileUploadTceForms */
49
+		$fileUpload = GeneralUtility::makeInstance(\Fab\Media\Form\FileUploadTceForms::class);
50
+		$fileUpload->setValue($fileMetadataRecord['file'][0])->setPrefix(MediaModule::getParameterPrefix());
51
+		$result['html'] = $fileUpload->render();
52
+		return $result;
53
+	}
54 54
 
55 55
 }
Please login to merge, or discard this patch.
Classes/FileUpload/UploadManager.php 1 patch
Indentation   +357 added lines, -357 removed lines patch added patch discarded remove patch
@@ -20,362 +20,362 @@
 block discarded – undo
20 20
 class UploadManager
21 21
 {
22 22
 
23
-    const UPLOAD_FOLDER = 'typo3temp/pics';
24
-
25
-    /**
26
-     * @var int|null|string
27
-     */
28
-    protected $sizeLimit;
29
-
30
-    /**
31
-     * @var string
32
-     */
33
-    protected $uploadFolder;
34
-
35
-    /**
36
-     * @var FormUtility
37
-     */
38
-    protected $formUtility;
39
-
40
-    /**
41
-     * @var \TYPO3\CMS\Core\Resource\ResourceStorage
42
-     */
43
-    protected $storage;
44
-
45
-    /**
46
-     * Name of the file input in the DOM.
47
-     *
48
-     * @var string
49
-     */
50
-    protected $inputName = 'qqfile';
51
-
52
-    /**
53
-     * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storage
54
-     * @return UploadManager
55
-     */
56
-    function __construct($storage = null)
57
-    {
58
-
59
-        $this->initializeUploadFolder();
60
-
61
-        // max file size in bytes
62
-        $this->sizeLimit = GeneralUtility::getMaxUploadFileSize() * 1024;
63
-        $this->checkServerSettings();
64
-
65
-        $this->formUtility = FormUtility::getInstance();
66
-        $this->storage = $storage;
67
-    }
68
-
69
-    /**
70
-     * Handle the uploaded file.
71
-     *
72
-     * @return UploadedFileInterface
73
-     */
74
-    public function handleUpload()
75
-    {
76
-
77
-        /** @var $uploadedFile UploadedFileInterface */
78
-        $uploadedFile = false;
79
-        if ($this->formUtility->isMultiparted()) {
80
-
81
-            // Default case
82
-            $uploadedFile = GeneralUtility::makeInstance(\Fab\Media\FileUpload\MultipartedFile::class);
83
-        } elseif ($this->formUtility->isOctetStreamed()) {
84
-
85
-            // Fine Upload plugin would use it if forceEncoded = false and paramsInBody = false
86
-            $uploadedFile = GeneralUtility::makeInstance(\Fab\Media\FileUpload\StreamedFile::class);
87
-        } elseif ($this->formUtility->isUrlEncoded()) {
88
-
89
-            // Used for image resizing in BE
90
-            $uploadedFile = GeneralUtility::makeInstance(\Fab\Media\FileUpload\Base64File::class);
91
-        }
92
-
93
-        if (!$uploadedFile) {
94
-            $this->throwException('Could not instantiate an upload object... No file was uploaded?');
95
-        }
96
-
97
-        $fileName = $this->getFileName($uploadedFile);
98
-
99
-        $this->checkFileSize($uploadedFile->getSize());
100
-        $this->checkFileAllowed($fileName);
101
-
102
-        $saved = $uploadedFile->setInputName($this->inputName)
103
-            ->setUploadFolder($this->uploadFolder)
104
-            ->setName($fileName)
105
-            ->save();
106
-
107
-        if (!$saved) {
108
-            $this->throwException('Could not save uploaded file. The upload was cancelled, or server error encountered');
109
-        }
110
-
111
-        // Optimize file if the uploaded file is an image.
112
-        if ($uploadedFile->getType() == \TYPO3\CMS\Core\Resource\File::FILETYPE_IMAGE) {
113
-            $uploadedFile = ImageOptimizer::getInstance($this->storage)->optimize($uploadedFile);
114
-        }
115
-        return $uploadedFile;
116
-    }
117
-
118
-    /**
119
-     * Internal function that checks if server's may sizes match the
120
-     * object's maximum size for uploads.
121
-     *
122
-     * @return void
123
-     */
124
-    protected function checkServerSettings()
125
-    {
126
-        $postSize = $this->toBytes(ini_get('post_max_size'));
127
-
128
-        $uploadSize = $this->toBytes(ini_get('upload_max_filesize'));
129
-
130
-        if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit) {
131
-            $size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';
132
-            $this->throwException('increase post_max_size and upload_max_filesize to ' . $size);
133
-        }
134
-    }
135
-
136
-    /**
137
-     * Convert a given size with units to bytes.
138
-     *
139
-     * @param string $str
140
-     * @return int|string
141
-     */
142
-    protected function toBytes($str)
143
-    {
144
-        $val = trim($str);
145
-        $last = strtolower($str[strlen($str) - 1]);
146
-        switch ($last) {
147
-            case 'g':
148
-                $val *= 1024;
149
-            case 'm':
150
-                $val *= 1024;
151
-            case 'k':
152
-                $val *= 1024;
153
-        }
154
-        return $val;
155
-    }
156
-
157
-    /**
158
-     * Return a file name given an uploaded file
159
-     *
160
-     * @param UploadedFileInterface $uploadedFile
161
-     * @return string
162
-     */
163
-    public function getFileName(UploadedFileInterface $uploadedFile)
164
-    {
165
-        $pathInfo = pathinfo($uploadedFile->getOriginalName());
166
-        $fileName = $this->sanitizeFileName($pathInfo['filename']);
167
-        $fileNameWithExtension = $fileName;
168
-        if (!empty($pathInfo['extension'])) {
169
-            $fileNameWithExtension = sprintf('%s.%s', $fileName, $pathInfo['extension']);
170
-        }
171
-        return $fileNameWithExtension;
172
-    }
173
-
174
-    /**
175
-     * Check whether the file size does not exceed the allowed limit
176
-     *
177
-     * @param int $size
178
-     */
179
-    public function checkFileSize($size)
180
-    {
181
-        if ($size == 0) {
182
-            $this->throwException('File is empty');
183
-        }
184
-
185
-        if ($size > $this->sizeLimit) {
186
-            $this->throwException('File is too large');
187
-        }
188
-    }
189
-
190
-    /**
191
-     * Check whether the file is allowed
192
-     *
193
-     * @param string $fileName
194
-     */
195
-    public function checkFileAllowed($fileName)
196
-    {
197
-        $isAllowed = $this->checkFileExtensionPermission($fileName);
198
-        if (!$isAllowed) {
199
-            $these = PermissionUtility::getInstance()->getAllowedExtensionList();
200
-            $this->throwException('File has an invalid extension, it should be one of ' . $these . '.');
201
-        }
202
-    }
203
-
204
-    /**
205
-     * If the fileName is given, check it against the
206
-     * TYPO3_CONF_VARS[BE][fileDenyPattern] + and if the file extension is allowed
207
-     *
208
-     * @see \TYPO3\CMS\Core\Resource\ResourceStorage->checkFileExtensionPermission($fileName);
209
-     * @param string $fileName Full filename
210
-     * @return boolean true if extension/filename is allowed
211
-     */
212
-    public function checkFileExtensionPermission($fileName)
213
-    {
214
-        $isAllowed = GeneralUtility::verifyFilenameAgainstDenyPattern($fileName);
215
-        if ($isAllowed) {
216
-            $fileInfo = GeneralUtility::split_fileref($fileName);
217
-            // Set up the permissions for the file extension
218
-            $fileExtensionPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']['webspace'];
219
-            $fileExtensionPermissions['allow'] = GeneralUtility::uniqueList(strtolower($fileExtensionPermissions['allow']));
220
-            $fileExtensionPermissions['deny'] = GeneralUtility::uniqueList(strtolower($fileExtensionPermissions['deny']));
221
-            $fileExtension = strtolower($fileInfo['fileext']);
222
-            if ($fileExtension !== '') {
223
-                // If the extension is found amongst the allowed types, we return true immediately
224
-                if ($fileExtensionPermissions['allow'] === '*' || GeneralUtility::inList($fileExtensionPermissions['allow'], $fileExtension)) {
225
-                    return true;
226
-                }
227
-                // If the extension is found amongst the denied types, we return false immediately
228
-                if ($fileExtensionPermissions['deny'] === '*' || GeneralUtility::inList($fileExtensionPermissions['deny'], $fileExtension)) {
229
-                    return false;
230
-                }
231
-                // If no match we return true
232
-                return true;
233
-            } else {
234
-                if ($fileExtensionPermissions['allow'] === '*') {
235
-                    return true;
236
-                }
237
-                if ($fileExtensionPermissions['deny'] === '*') {
238
-                    return false;
239
-                }
240
-                return true;
241
-            }
242
-        }
243
-        return false;
244
-    }
245
-
246
-    /**
247
-     * Sanitize the file name for the web.
248
-     * It has been noticed issues when letting done this work by FAL. Give it a little hand.
249
-     *
250
-     * @see https://github.com/alixaxel/phunction/blob/master/phunction/Text.php#L252
251
-     * @param string $fileName
252
-     * @param string $slug
253
-     * @param string $extra
254
-     * @return string
255
-     */
256
-    public function sanitizeFileName($fileName, $slug = '-', $extra = null)
257
-    {
258
-        return trim(preg_replace('~[^0-9a-z_' . preg_quote($extra, '~') . ']+~i', $slug, $this->unAccent($fileName)), $slug);
259
-    }
260
-
261
-    /**
262
-     * Remove accent from a string
263
-     *
264
-     * @see https://github.com/alixaxel/phunction/blob/master/phunction/Text.php#L297
265
-     * @param $string
266
-     * @return string
267
-     */
268
-    protected function unAccent($string)
269
-    {
270
-        $searches = array('ç', 'æ', 'œ', 'á', 'é', 'í', 'ó', 'ú', 'à', 'è', 'ì', 'ò', 'ù', 'ä', 'ë', 'ï', 'ö', 'ü', 'ÿ', 'â', 'ê', 'î', 'ô', 'û', 'å', 'e', 'i', 'ø', 'u');
271
-        $replaces = array('c', 'ae', 'oe', 'a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o', 'u', 'y', 'a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o', 'u');
272
-        $sanitizedString = str_replace($searches, $replaces, $string);
273
-
274
-        if (extension_loaded('intl') === true) {
275
-            $sanitizedString = \Normalizer::normalize($sanitizedString, \Normalizer::FORM_KD);
276
-        }
277
-        return $sanitizedString;
278
-    }
279
-
280
-    /**
281
-     * @throws FailedFileUploadException
282
-     * @param string $message
283
-     */
284
-    protected function throwException($message)
285
-    {
286
-        throw new FailedFileUploadException($message, 1357510420);
287
-    }
288
-
289
-    /**
290
-     * Initialize Upload Folder.
291
-     *
292
-     * @return void
293
-     */
294
-    protected function initializeUploadFolder()
295
-    {
296
-        $this->uploadFolder = PATH_site . self::UPLOAD_FOLDER;
297
-
298
-        // Initialize the upload folder for file transfer and create it if not yet existing
299
-        if (!file_exists($this->uploadFolder)) {
300
-            GeneralUtility::mkdir($this->uploadFolder);
301
-        }
302
-
303
-        // Check whether the upload folder is writable
304
-        if (!is_writable($this->uploadFolder)) {
305
-            $this->throwException("Server error. Upload directory isn't writable.");
306
-        }
307
-    }
308
-
309
-    /**
310
-     * @return int|null|string
311
-     */
312
-    public function getSizeLimit()
313
-    {
314
-        return $this->sizeLimit;
315
-    }
316
-
317
-    /**
318
-     * @param int|null|string $sizeLimit
319
-     * @return $this
320
-     */
321
-    public function setSizeLimit($sizeLimit)
322
-    {
323
-        $this->sizeLimit = $sizeLimit;
324
-        return $this;
325
-    }
326
-
327
-    /**
328
-     * @return string
329
-     */
330
-    public function getUploadFolder()
331
-    {
332
-        return $this->uploadFolder;
333
-    }
334
-
335
-    /**
336
-     * @param string $uploadFolder
337
-     * @return $this
338
-     */
339
-    public function setUploadFolder($uploadFolder)
340
-    {
341
-        $this->uploadFolder = $uploadFolder;
342
-        return $this;
343
-    }
344
-
345
-    /**
346
-     * @return string
347
-     */
348
-    public function getInputName()
349
-    {
350
-        return $this->inputName;
351
-    }
352
-
353
-    /**
354
-     * @param string $inputName
355
-     * @return $this
356
-     */
357
-    public function setInputName($inputName)
358
-    {
359
-        $this->inputName = $inputName;
360
-        return $this;
361
-    }
362
-
363
-    /**
364
-     * @return \TYPO3\CMS\Core\Resource\ResourceStorage
365
-     */
366
-    public function getStorage()
367
-    {
368
-        return $this->storage;
369
-    }
370
-
371
-    /**
372
-     * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storage
373
-     * @return $this
374
-     */
375
-    public function setStorage($storage)
376
-    {
377
-        $this->storage = $storage;
378
-        return $this;
379
-    }
23
+	const UPLOAD_FOLDER = 'typo3temp/pics';
24
+
25
+	/**
26
+	 * @var int|null|string
27
+	 */
28
+	protected $sizeLimit;
29
+
30
+	/**
31
+	 * @var string
32
+	 */
33
+	protected $uploadFolder;
34
+
35
+	/**
36
+	 * @var FormUtility
37
+	 */
38
+	protected $formUtility;
39
+
40
+	/**
41
+	 * @var \TYPO3\CMS\Core\Resource\ResourceStorage
42
+	 */
43
+	protected $storage;
44
+
45
+	/**
46
+	 * Name of the file input in the DOM.
47
+	 *
48
+	 * @var string
49
+	 */
50
+	protected $inputName = 'qqfile';
51
+
52
+	/**
53
+	 * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storage
54
+	 * @return UploadManager
55
+	 */
56
+	function __construct($storage = null)
57
+	{
58
+
59
+		$this->initializeUploadFolder();
60
+
61
+		// max file size in bytes
62
+		$this->sizeLimit = GeneralUtility::getMaxUploadFileSize() * 1024;
63
+		$this->checkServerSettings();
64
+
65
+		$this->formUtility = FormUtility::getInstance();
66
+		$this->storage = $storage;
67
+	}
68
+
69
+	/**
70
+	 * Handle the uploaded file.
71
+	 *
72
+	 * @return UploadedFileInterface
73
+	 */
74
+	public function handleUpload()
75
+	{
76
+
77
+		/** @var $uploadedFile UploadedFileInterface */
78
+		$uploadedFile = false;
79
+		if ($this->formUtility->isMultiparted()) {
80
+
81
+			// Default case
82
+			$uploadedFile = GeneralUtility::makeInstance(\Fab\Media\FileUpload\MultipartedFile::class);
83
+		} elseif ($this->formUtility->isOctetStreamed()) {
84
+
85
+			// Fine Upload plugin would use it if forceEncoded = false and paramsInBody = false
86
+			$uploadedFile = GeneralUtility::makeInstance(\Fab\Media\FileUpload\StreamedFile::class);
87
+		} elseif ($this->formUtility->isUrlEncoded()) {
88
+
89
+			// Used for image resizing in BE
90
+			$uploadedFile = GeneralUtility::makeInstance(\Fab\Media\FileUpload\Base64File::class);
91
+		}
92
+
93
+		if (!$uploadedFile) {
94
+			$this->throwException('Could not instantiate an upload object... No file was uploaded?');
95
+		}
96
+
97
+		$fileName = $this->getFileName($uploadedFile);
98
+
99
+		$this->checkFileSize($uploadedFile->getSize());
100
+		$this->checkFileAllowed($fileName);
101
+
102
+		$saved = $uploadedFile->setInputName($this->inputName)
103
+			->setUploadFolder($this->uploadFolder)
104
+			->setName($fileName)
105
+			->save();
106
+
107
+		if (!$saved) {
108
+			$this->throwException('Could not save uploaded file. The upload was cancelled, or server error encountered');
109
+		}
110
+
111
+		// Optimize file if the uploaded file is an image.
112
+		if ($uploadedFile->getType() == \TYPO3\CMS\Core\Resource\File::FILETYPE_IMAGE) {
113
+			$uploadedFile = ImageOptimizer::getInstance($this->storage)->optimize($uploadedFile);
114
+		}
115
+		return $uploadedFile;
116
+	}
117
+
118
+	/**
119
+	 * Internal function that checks if server's may sizes match the
120
+	 * object's maximum size for uploads.
121
+	 *
122
+	 * @return void
123
+	 */
124
+	protected function checkServerSettings()
125
+	{
126
+		$postSize = $this->toBytes(ini_get('post_max_size'));
127
+
128
+		$uploadSize = $this->toBytes(ini_get('upload_max_filesize'));
129
+
130
+		if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit) {
131
+			$size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';
132
+			$this->throwException('increase post_max_size and upload_max_filesize to ' . $size);
133
+		}
134
+	}
135
+
136
+	/**
137
+	 * Convert a given size with units to bytes.
138
+	 *
139
+	 * @param string $str
140
+	 * @return int|string
141
+	 */
142
+	protected function toBytes($str)
143
+	{
144
+		$val = trim($str);
145
+		$last = strtolower($str[strlen($str) - 1]);
146
+		switch ($last) {
147
+			case 'g':
148
+				$val *= 1024;
149
+			case 'm':
150
+				$val *= 1024;
151
+			case 'k':
152
+				$val *= 1024;
153
+		}
154
+		return $val;
155
+	}
156
+
157
+	/**
158
+	 * Return a file name given an uploaded file
159
+	 *
160
+	 * @param UploadedFileInterface $uploadedFile
161
+	 * @return string
162
+	 */
163
+	public function getFileName(UploadedFileInterface $uploadedFile)
164
+	{
165
+		$pathInfo = pathinfo($uploadedFile->getOriginalName());
166
+		$fileName = $this->sanitizeFileName($pathInfo['filename']);
167
+		$fileNameWithExtension = $fileName;
168
+		if (!empty($pathInfo['extension'])) {
169
+			$fileNameWithExtension = sprintf('%s.%s', $fileName, $pathInfo['extension']);
170
+		}
171
+		return $fileNameWithExtension;
172
+	}
173
+
174
+	/**
175
+	 * Check whether the file size does not exceed the allowed limit
176
+	 *
177
+	 * @param int $size
178
+	 */
179
+	public function checkFileSize($size)
180
+	{
181
+		if ($size == 0) {
182
+			$this->throwException('File is empty');
183
+		}
184
+
185
+		if ($size > $this->sizeLimit) {
186
+			$this->throwException('File is too large');
187
+		}
188
+	}
189
+
190
+	/**
191
+	 * Check whether the file is allowed
192
+	 *
193
+	 * @param string $fileName
194
+	 */
195
+	public function checkFileAllowed($fileName)
196
+	{
197
+		$isAllowed = $this->checkFileExtensionPermission($fileName);
198
+		if (!$isAllowed) {
199
+			$these = PermissionUtility::getInstance()->getAllowedExtensionList();
200
+			$this->throwException('File has an invalid extension, it should be one of ' . $these . '.');
201
+		}
202
+	}
203
+
204
+	/**
205
+	 * If the fileName is given, check it against the
206
+	 * TYPO3_CONF_VARS[BE][fileDenyPattern] + and if the file extension is allowed
207
+	 *
208
+	 * @see \TYPO3\CMS\Core\Resource\ResourceStorage->checkFileExtensionPermission($fileName);
209
+	 * @param string $fileName Full filename
210
+	 * @return boolean true if extension/filename is allowed
211
+	 */
212
+	public function checkFileExtensionPermission($fileName)
213
+	{
214
+		$isAllowed = GeneralUtility::verifyFilenameAgainstDenyPattern($fileName);
215
+		if ($isAllowed) {
216
+			$fileInfo = GeneralUtility::split_fileref($fileName);
217
+			// Set up the permissions for the file extension
218
+			$fileExtensionPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']['webspace'];
219
+			$fileExtensionPermissions['allow'] = GeneralUtility::uniqueList(strtolower($fileExtensionPermissions['allow']));
220
+			$fileExtensionPermissions['deny'] = GeneralUtility::uniqueList(strtolower($fileExtensionPermissions['deny']));
221
+			$fileExtension = strtolower($fileInfo['fileext']);
222
+			if ($fileExtension !== '') {
223
+				// If the extension is found amongst the allowed types, we return true immediately
224
+				if ($fileExtensionPermissions['allow'] === '*' || GeneralUtility::inList($fileExtensionPermissions['allow'], $fileExtension)) {
225
+					return true;
226
+				}
227
+				// If the extension is found amongst the denied types, we return false immediately
228
+				if ($fileExtensionPermissions['deny'] === '*' || GeneralUtility::inList($fileExtensionPermissions['deny'], $fileExtension)) {
229
+					return false;
230
+				}
231
+				// If no match we return true
232
+				return true;
233
+			} else {
234
+				if ($fileExtensionPermissions['allow'] === '*') {
235
+					return true;
236
+				}
237
+				if ($fileExtensionPermissions['deny'] === '*') {
238
+					return false;
239
+				}
240
+				return true;
241
+			}
242
+		}
243
+		return false;
244
+	}
245
+
246
+	/**
247
+	 * Sanitize the file name for the web.
248
+	 * It has been noticed issues when letting done this work by FAL. Give it a little hand.
249
+	 *
250
+	 * @see https://github.com/alixaxel/phunction/blob/master/phunction/Text.php#L252
251
+	 * @param string $fileName
252
+	 * @param string $slug
253
+	 * @param string $extra
254
+	 * @return string
255
+	 */
256
+	public function sanitizeFileName($fileName, $slug = '-', $extra = null)
257
+	{
258
+		return trim(preg_replace('~[^0-9a-z_' . preg_quote($extra, '~') . ']+~i', $slug, $this->unAccent($fileName)), $slug);
259
+	}
260
+
261
+	/**
262
+	 * Remove accent from a string
263
+	 *
264
+	 * @see https://github.com/alixaxel/phunction/blob/master/phunction/Text.php#L297
265
+	 * @param $string
266
+	 * @return string
267
+	 */
268
+	protected function unAccent($string)
269
+	{
270
+		$searches = array('ç', 'æ', 'œ', 'á', 'é', 'í', 'ó', 'ú', 'à', 'è', 'ì', 'ò', 'ù', 'ä', 'ë', 'ï', 'ö', 'ü', 'ÿ', 'â', 'ê', 'î', 'ô', 'û', 'å', 'e', 'i', 'ø', 'u');
271
+		$replaces = array('c', 'ae', 'oe', 'a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o', 'u', 'y', 'a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o', 'u');
272
+		$sanitizedString = str_replace($searches, $replaces, $string);
273
+
274
+		if (extension_loaded('intl') === true) {
275
+			$sanitizedString = \Normalizer::normalize($sanitizedString, \Normalizer::FORM_KD);
276
+		}
277
+		return $sanitizedString;
278
+	}
279
+
280
+	/**
281
+	 * @throws FailedFileUploadException
282
+	 * @param string $message
283
+	 */
284
+	protected function throwException($message)
285
+	{
286
+		throw new FailedFileUploadException($message, 1357510420);
287
+	}
288
+
289
+	/**
290
+	 * Initialize Upload Folder.
291
+	 *
292
+	 * @return void
293
+	 */
294
+	protected function initializeUploadFolder()
295
+	{
296
+		$this->uploadFolder = PATH_site . self::UPLOAD_FOLDER;
297
+
298
+		// Initialize the upload folder for file transfer and create it if not yet existing
299
+		if (!file_exists($this->uploadFolder)) {
300
+			GeneralUtility::mkdir($this->uploadFolder);
301
+		}
302
+
303
+		// Check whether the upload folder is writable
304
+		if (!is_writable($this->uploadFolder)) {
305
+			$this->throwException("Server error. Upload directory isn't writable.");
306
+		}
307
+	}
308
+
309
+	/**
310
+	 * @return int|null|string
311
+	 */
312
+	public function getSizeLimit()
313
+	{
314
+		return $this->sizeLimit;
315
+	}
316
+
317
+	/**
318
+	 * @param int|null|string $sizeLimit
319
+	 * @return $this
320
+	 */
321
+	public function setSizeLimit($sizeLimit)
322
+	{
323
+		$this->sizeLimit = $sizeLimit;
324
+		return $this;
325
+	}
326
+
327
+	/**
328
+	 * @return string
329
+	 */
330
+	public function getUploadFolder()
331
+	{
332
+		return $this->uploadFolder;
333
+	}
334
+
335
+	/**
336
+	 * @param string $uploadFolder
337
+	 * @return $this
338
+	 */
339
+	public function setUploadFolder($uploadFolder)
340
+	{
341
+		$this->uploadFolder = $uploadFolder;
342
+		return $this;
343
+	}
344
+
345
+	/**
346
+	 * @return string
347
+	 */
348
+	public function getInputName()
349
+	{
350
+		return $this->inputName;
351
+	}
352
+
353
+	/**
354
+	 * @param string $inputName
355
+	 * @return $this
356
+	 */
357
+	public function setInputName($inputName)
358
+	{
359
+		$this->inputName = $inputName;
360
+		return $this;
361
+	}
362
+
363
+	/**
364
+	 * @return \TYPO3\CMS\Core\Resource\ResourceStorage
365
+	 */
366
+	public function getStorage()
367
+	{
368
+		return $this->storage;
369
+	}
370
+
371
+	/**
372
+	 * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storage
373
+	 * @return $this
374
+	 */
375
+	public function setStorage($storage)
376
+	{
377
+		$this->storage = $storage;
378
+		return $this;
379
+	}
380 380
 
381 381
 }
Please login to merge, or discard this patch.
Classes/FileUpload/Optimizer/Resize.php 1 patch
Indentation   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -18,118 +18,118 @@
 block discarded – undo
18 18
 class Resize implements ImageOptimizerInterface
19 19
 {
20 20
 
21
-    /**
22
-     * @var \TYPO3\CMS\Frontend\Imaging\GifBuilder
23
-     */
24
-    protected $gifCreator;
25
-
26
-    /**
27
-     * @var \TYPO3\CMS\Core\Resource\ResourceStorage
28
-     */
29
-    protected $storage;
30
-
31
-    /**
32
-     * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storage
33
-     * @return Resize
34
-     */
35
-    public function __construct($storage = null)
36
-    {
37
-        $this->storage = $storage;
38
-        $this->gifCreator = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\Imaging\GifBuilder::class);
39
-        $this->gifCreator->init();
40
-        $this->gifCreator->absPrefix = PATH_site;
41
-    }
42
-
43
-    /**
44
-     * Optimize the given uploaded image.
45
-     *
46
-     * @param \Fab\Media\FileUpload\UploadedFileInterface $uploadedFile
47
-     * @return \Fab\Media\FileUpload\UploadedFileInterface
48
-     */
49
-    public function optimize($uploadedFile)
50
-    {
51
-
52
-        $imageInfo = getimagesize($uploadedFile->getFileWithAbsolutePath());
53
-
54
-        $currentWidth = $imageInfo[0];
55
-        $currentHeight = $imageInfo[1];
56
-
57
-        // resize an image if this one is bigger than telling by the settings.
58
-        if (is_object($this->storage)) {
59
-            $storageRecord = $this->storage->getStorageRecord();
60
-        } else {
61
-            // Will only work in the BE for now.
62
-            $storage = $this->getMediaModule()->getCurrentStorage();
63
-            $storageRecord = $storage->getStorageRecord();
64
-        }
65
-
66
-        if (strlen($storageRecord['maximum_dimension_original_image']) > 0) {
67
-
68
-            /** @var \Fab\Media\Dimension $imageDimension */
69
-            $imageDimension = GeneralUtility::makeInstance(\Fab\Media\Dimension::class, $storageRecord['maximum_dimension_original_image']);
70
-            if ($currentWidth > $imageDimension->getWidth() || $currentHeight > $imageDimension->getHeight()) {
71
-
72
-                // resize taking the width as reference
73
-                $this->resize($uploadedFile->getFileWithAbsolutePath(), $imageDimension->getWidth(), $imageDimension->getHeight());
74
-            }
75
-        }
76
-        return $uploadedFile;
77
-    }
78
-
79
-    /**
80
-     * Resize an image according to given parameter.
81
-     *
82
-     * @throws \Exception
83
-     * @param string $fileNameAndPath
84
-     * @param int $width
85
-     * @param int $height
86
-     * @return void
87
-     */
88
-    public function resize($fileNameAndPath, $width = 0, $height = 0)
89
-    {
90
-
91
-        // Skip profile of the image
92
-        $imParams = '###SkipStripProfile###';
93
-        $options = array(
94
-            'maxW' => $width,
95
-            'maxH' => $height,
96
-        );
97
-
98
-        $tempFileInfo = $this->gifCreator->imageMagickConvert($fileNameAndPath, '', '', '', $imParams, '', $options, true);
99
-        if ($tempFileInfo) {
100
-
101
-            // Overwrite original file
102
-            @unlink($fileNameAndPath);
103
-            @rename($tempFileInfo[3], $fileNameAndPath);
104
-        }
105
-    }
106
-
107
-    /**
108
-     * Escapes a file name so it can safely be used on the command line.
109
-     *
110
-     * @see \TYPO3\CMS\Core\Imaging\GraphicalFunctions
111
-     * @param string $inputName filename to safeguard, must not be empty
112
-     * @return string $inputName escaped as needed
113
-     */
114
-    protected function wrapFileName($inputName)
115
-    {
116
-        if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
117
-            $currentLocale = setlocale(LC_CTYPE, 0);
118
-            setlocale(LC_CTYPE, $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLocale']);
119
-        }
120
-        $escapedInputName = escapeshellarg($inputName);
121
-        if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
122
-            setlocale(LC_CTYPE, $currentLocale);
123
-        }
124
-        return $escapedInputName;
125
-    }
126
-
127
-    /**
128
-     * @return MediaModule|object
129
-     */
130
-    protected function getMediaModule()
131
-    {
132
-        return GeneralUtility::makeInstance(\Fab\Media\Module\MediaModule::class);
133
-    }
21
+	/**
22
+	 * @var \TYPO3\CMS\Frontend\Imaging\GifBuilder
23
+	 */
24
+	protected $gifCreator;
25
+
26
+	/**
27
+	 * @var \TYPO3\CMS\Core\Resource\ResourceStorage
28
+	 */
29
+	protected $storage;
30
+
31
+	/**
32
+	 * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storage
33
+	 * @return Resize
34
+	 */
35
+	public function __construct($storage = null)
36
+	{
37
+		$this->storage = $storage;
38
+		$this->gifCreator = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\Imaging\GifBuilder::class);
39
+		$this->gifCreator->init();
40
+		$this->gifCreator->absPrefix = PATH_site;
41
+	}
42
+
43
+	/**
44
+	 * Optimize the given uploaded image.
45
+	 *
46
+	 * @param \Fab\Media\FileUpload\UploadedFileInterface $uploadedFile
47
+	 * @return \Fab\Media\FileUpload\UploadedFileInterface
48
+	 */
49
+	public function optimize($uploadedFile)
50
+	{
51
+
52
+		$imageInfo = getimagesize($uploadedFile->getFileWithAbsolutePath());
53
+
54
+		$currentWidth = $imageInfo[0];
55
+		$currentHeight = $imageInfo[1];
56
+
57
+		// resize an image if this one is bigger than telling by the settings.
58
+		if (is_object($this->storage)) {
59
+			$storageRecord = $this->storage->getStorageRecord();
60
+		} else {
61
+			// Will only work in the BE for now.
62
+			$storage = $this->getMediaModule()->getCurrentStorage();
63
+			$storageRecord = $storage->getStorageRecord();
64
+		}
65
+
66
+		if (strlen($storageRecord['maximum_dimension_original_image']) > 0) {
67
+
68
+			/** @var \Fab\Media\Dimension $imageDimension */
69
+			$imageDimension = GeneralUtility::makeInstance(\Fab\Media\Dimension::class, $storageRecord['maximum_dimension_original_image']);
70
+			if ($currentWidth > $imageDimension->getWidth() || $currentHeight > $imageDimension->getHeight()) {
71
+
72
+				// resize taking the width as reference
73
+				$this->resize($uploadedFile->getFileWithAbsolutePath(), $imageDimension->getWidth(), $imageDimension->getHeight());
74
+			}
75
+		}
76
+		return $uploadedFile;
77
+	}
78
+
79
+	/**
80
+	 * Resize an image according to given parameter.
81
+	 *
82
+	 * @throws \Exception
83
+	 * @param string $fileNameAndPath
84
+	 * @param int $width
85
+	 * @param int $height
86
+	 * @return void
87
+	 */
88
+	public function resize($fileNameAndPath, $width = 0, $height = 0)
89
+	{
90
+
91
+		// Skip profile of the image
92
+		$imParams = '###SkipStripProfile###';
93
+		$options = array(
94
+			'maxW' => $width,
95
+			'maxH' => $height,
96
+		);
97
+
98
+		$tempFileInfo = $this->gifCreator->imageMagickConvert($fileNameAndPath, '', '', '', $imParams, '', $options, true);
99
+		if ($tempFileInfo) {
100
+
101
+			// Overwrite original file
102
+			@unlink($fileNameAndPath);
103
+			@rename($tempFileInfo[3], $fileNameAndPath);
104
+		}
105
+	}
106
+
107
+	/**
108
+	 * Escapes a file name so it can safely be used on the command line.
109
+	 *
110
+	 * @see \TYPO3\CMS\Core\Imaging\GraphicalFunctions
111
+	 * @param string $inputName filename to safeguard, must not be empty
112
+	 * @return string $inputName escaped as needed
113
+	 */
114
+	protected function wrapFileName($inputName)
115
+	{
116
+		if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
117
+			$currentLocale = setlocale(LC_CTYPE, 0);
118
+			setlocale(LC_CTYPE, $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLocale']);
119
+		}
120
+		$escapedInputName = escapeshellarg($inputName);
121
+		if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
122
+			setlocale(LC_CTYPE, $currentLocale);
123
+		}
124
+		return $escapedInputName;
125
+	}
126
+
127
+	/**
128
+	 * @return MediaModule|object
129
+	 */
130
+	protected function getMediaModule()
131
+	{
132
+		return GeneralUtility::makeInstance(\Fab\Media\Module\MediaModule::class);
133
+	}
134 134
 
135 135
 }
Please login to merge, or discard this patch.
Classes/FileUpload/Optimizer/Rotate.php 1 patch
Indentation   +149 added lines, -149 removed lines patch added patch discarded remove patch
@@ -17,154 +17,154 @@
 block discarded – undo
17 17
 class Rotate implements ImageOptimizerInterface
18 18
 {
19 19
 
20
-    /**
21
-     * @var \TYPO3\CMS\Frontend\Imaging\GifBuilder
22
-     */
23
-    protected $gifCreator;
24
-
25
-    /**
26
-     * @return \Fab\Media\FileUpload\Optimizer\Rotate
27
-     */
28
-    public function __construct()
29
-    {
30
-        $this->gifCreator = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\Imaging\GifBuilder::class);
31
-        $this->gifCreator->init();
32
-        $this->gifCreator->absPrefix = PATH_site;
33
-    }
34
-
35
-    /**
36
-     * Optimize the given uploaded image
37
-     *
38
-     * @param \Fab\Media\FileUpload\UploadedFileInterface $uploadedFile
39
-     * @return \Fab\Media\FileUpload\UploadedFileInterface
40
-     */
41
-    public function optimize($uploadedFile)
42
-    {
43
-
44
-        $orientation = $this->getOrientation($uploadedFile->getFileWithAbsolutePath());
45
-        $isRotated = $this->isRotated($orientation);
46
-
47
-        // Only rotate image if necessary!
48
-        if ($isRotated > 0) {
49
-            $transformation = $this->getTransformation($orientation);
50
-
51
-            $imParams = '###SkipStripProfile###';
52
-            if ($transformation !== '') {
53
-                $imParams .= ' ' . $transformation;
54
-            }
55
-
56
-            $tempFileInfo = $this->gifCreator->imageMagickConvert($uploadedFile->getFileWithAbsolutePath(), '', '', '', $imParams, '', [], true);
57
-            if ($tempFileInfo) {
58
-                // Replace original file
59
-                @unlink($uploadedFile->getFileWithAbsolutePath());
60
-                @rename($tempFileInfo[3], $uploadedFile->getFileWithAbsolutePath());
61
-
62
-                if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_version_5'] === 'gm') {
63
-                    $this->resetOrientation($uploadedFile->getFileWithAbsolutePath());
64
-                }
65
-            }
66
-        }
67
-        return $uploadedFile;
68
-    }
69
-
70
-    /**
71
-     * Returns the EXIF orientation of a given picture.
72
-     *
73
-     * @param string $filename
74
-     * @return integer
75
-     */
76
-    protected function getOrientation($filename)
77
-    {
78
-        $extension = strtolower(substr($filename, strrpos($filename, '.') + 1));
79
-        $orientation = 1; // Fallback to "straight"
80
-        if (\TYPO3\CMS\Core\Utility\GeneralUtility::inList('jpg,jpeg,tif,tiff', $extension) && function_exists('exif_read_data')) {
81
-            try {
82
-                $exif = exif_read_data($filename);
83
-                if ($exif) {
84
-                    $orientation = $exif['Orientation'];
85
-                }
86
-            } catch (\Exception $e) {}
87
-        }
88
-        return $orientation;
89
-    }
90
-
91
-    /**
92
-     * Returns true if the given picture is rotated.
93
-     *
94
-     * @param integer $orientation EXIF orientation
95
-     * @return integer
96
-     * @see http://www.impulseadventure.com/photo/exif-orientation.html
97
-     */
98
-    protected function isRotated($orientation)
99
-    {
100
-        $ret = false;
101
-        switch ($orientation) {
102
-            case 2: // horizontal flip
103
-            case 3: // 180°
104
-            case 4: // vertical flip
105
-            case 5: // vertical flip + 90 rotate right
106
-            case 6: // 90° rotate right
107
-            case 7: // horizontal flip + 90 rotate right
108
-            case 8: // 90° rotate left
109
-                $ret = true;
110
-                break;
111
-        }
112
-        return $ret;
113
-    }
114
-
115
-    /**
116
-     * Returns a command line parameter to fix the orientation of a rotated picture.
117
-     *
118
-     * @param integer $orientation
119
-     * @return string
120
-     */
121
-    protected function getTransformation($orientation)
122
-    {
123
-        $transformation = '';
124
-        if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_version_5'] !== 'gm') {
125
-            // ImageMagick
126
-            if ($orientation >= 2 && $orientation <= 8) {
127
-                $transformation = '-auto-orient';
128
-            }
129
-        } else {
130
-            // GraphicsMagick
131
-            switch ($orientation) {
132
-                case 2: // horizontal flip
133
-                    $transformation = '-flip horizontal';
134
-                    break;
135
-                case 3: // 180°
136
-                    $transformation = '-rotate 180';
137
-                    break;
138
-                case 4: // vertical flip
139
-                    $transformation = '-flip vertical';
140
-                    break;
141
-                case 5: // vertical flip + 90 rotate right
142
-                    $transformation = '-transpose';
143
-                    break;
144
-                case 6: // 90° rotate right
145
-                    $transformation = '-rotate 90';
146
-                    break;
147
-                case 7: // horizontal flip + 90 rotate right
148
-                    $transformation = '-transverse';
149
-                    break;
150
-                case 8: // 90° rotate left
151
-                    $transformation = '-rotate 270';
152
-                    break;
153
-            }
154
-        }
155
-        return $transformation;
156
-    }
157
-
158
-    /**
159
-     * Resets the EXIF orientation flag of a picture.
160
-     *
161
-     * @param string $filename
162
-     * @return void
163
-     * @see http://sylvana.net/jpegcrop/exif_orientation.html
164
-     */
165
-    protected function resetOrientation($filename)
166
-    {
167
-        JpegExifOrient::setOrientation($filename, 1);
168
-    }
20
+	/**
21
+	 * @var \TYPO3\CMS\Frontend\Imaging\GifBuilder
22
+	 */
23
+	protected $gifCreator;
24
+
25
+	/**
26
+	 * @return \Fab\Media\FileUpload\Optimizer\Rotate
27
+	 */
28
+	public function __construct()
29
+	{
30
+		$this->gifCreator = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\Imaging\GifBuilder::class);
31
+		$this->gifCreator->init();
32
+		$this->gifCreator->absPrefix = PATH_site;
33
+	}
34
+
35
+	/**
36
+	 * Optimize the given uploaded image
37
+	 *
38
+	 * @param \Fab\Media\FileUpload\UploadedFileInterface $uploadedFile
39
+	 * @return \Fab\Media\FileUpload\UploadedFileInterface
40
+	 */
41
+	public function optimize($uploadedFile)
42
+	{
43
+
44
+		$orientation = $this->getOrientation($uploadedFile->getFileWithAbsolutePath());
45
+		$isRotated = $this->isRotated($orientation);
46
+
47
+		// Only rotate image if necessary!
48
+		if ($isRotated > 0) {
49
+			$transformation = $this->getTransformation($orientation);
50
+
51
+			$imParams = '###SkipStripProfile###';
52
+			if ($transformation !== '') {
53
+				$imParams .= ' ' . $transformation;
54
+			}
55
+
56
+			$tempFileInfo = $this->gifCreator->imageMagickConvert($uploadedFile->getFileWithAbsolutePath(), '', '', '', $imParams, '', [], true);
57
+			if ($tempFileInfo) {
58
+				// Replace original file
59
+				@unlink($uploadedFile->getFileWithAbsolutePath());
60
+				@rename($tempFileInfo[3], $uploadedFile->getFileWithAbsolutePath());
61
+
62
+				if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_version_5'] === 'gm') {
63
+					$this->resetOrientation($uploadedFile->getFileWithAbsolutePath());
64
+				}
65
+			}
66
+		}
67
+		return $uploadedFile;
68
+	}
69
+
70
+	/**
71
+	 * Returns the EXIF orientation of a given picture.
72
+	 *
73
+	 * @param string $filename
74
+	 * @return integer
75
+	 */
76
+	protected function getOrientation($filename)
77
+	{
78
+		$extension = strtolower(substr($filename, strrpos($filename, '.') + 1));
79
+		$orientation = 1; // Fallback to "straight"
80
+		if (\TYPO3\CMS\Core\Utility\GeneralUtility::inList('jpg,jpeg,tif,tiff', $extension) && function_exists('exif_read_data')) {
81
+			try {
82
+				$exif = exif_read_data($filename);
83
+				if ($exif) {
84
+					$orientation = $exif['Orientation'];
85
+				}
86
+			} catch (\Exception $e) {}
87
+		}
88
+		return $orientation;
89
+	}
90
+
91
+	/**
92
+	 * Returns true if the given picture is rotated.
93
+	 *
94
+	 * @param integer $orientation EXIF orientation
95
+	 * @return integer
96
+	 * @see http://www.impulseadventure.com/photo/exif-orientation.html
97
+	 */
98
+	protected function isRotated($orientation)
99
+	{
100
+		$ret = false;
101
+		switch ($orientation) {
102
+			case 2: // horizontal flip
103
+			case 3: // 180°
104
+			case 4: // vertical flip
105
+			case 5: // vertical flip + 90 rotate right
106
+			case 6: // 90° rotate right
107
+			case 7: // horizontal flip + 90 rotate right
108
+			case 8: // 90° rotate left
109
+				$ret = true;
110
+				break;
111
+		}
112
+		return $ret;
113
+	}
114
+
115
+	/**
116
+	 * Returns a command line parameter to fix the orientation of a rotated picture.
117
+	 *
118
+	 * @param integer $orientation
119
+	 * @return string
120
+	 */
121
+	protected function getTransformation($orientation)
122
+	{
123
+		$transformation = '';
124
+		if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_version_5'] !== 'gm') {
125
+			// ImageMagick
126
+			if ($orientation >= 2 && $orientation <= 8) {
127
+				$transformation = '-auto-orient';
128
+			}
129
+		} else {
130
+			// GraphicsMagick
131
+			switch ($orientation) {
132
+				case 2: // horizontal flip
133
+					$transformation = '-flip horizontal';
134
+					break;
135
+				case 3: // 180°
136
+					$transformation = '-rotate 180';
137
+					break;
138
+				case 4: // vertical flip
139
+					$transformation = '-flip vertical';
140
+					break;
141
+				case 5: // vertical flip + 90 rotate right
142
+					$transformation = '-transpose';
143
+					break;
144
+				case 6: // 90° rotate right
145
+					$transformation = '-rotate 90';
146
+					break;
147
+				case 7: // horizontal flip + 90 rotate right
148
+					$transformation = '-transverse';
149
+					break;
150
+				case 8: // 90° rotate left
151
+					$transformation = '-rotate 270';
152
+					break;
153
+			}
154
+		}
155
+		return $transformation;
156
+	}
157
+
158
+	/**
159
+	 * Resets the EXIF orientation flag of a picture.
160
+	 *
161
+	 * @param string $filename
162
+	 * @return void
163
+	 * @see http://sylvana.net/jpegcrop/exif_orientation.html
164
+	 */
165
+	protected function resetOrientation($filename)
166
+	{
167
+		JpegExifOrient::setOrientation($filename, 1);
168
+	}
169 169
 
170 170
 }
Please login to merge, or discard this patch.
Classes/FileUpload/FormUtility.php 1 patch
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -16,54 +16,54 @@
 block discarded – undo
16 16
 class FormUtility implements SingletonInterface
17 17
 {
18 18
 
19
-    /**
20
-     * Returns a class instance.
21
-     *
22
-     * @return \Fab\Media\FileUpload\FormUtility|object
23
-     */
24
-    static public function getInstance()
25
-    {
26
-        return \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\Fab\Media\FileUpload\FormUtility::class);
27
-    }
19
+	/**
20
+	 * Returns a class instance.
21
+	 *
22
+	 * @return \Fab\Media\FileUpload\FormUtility|object
23
+	 */
24
+	static public function getInstance()
25
+	{
26
+		return \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\Fab\Media\FileUpload\FormUtility::class);
27
+	}
28 28
 
29
-    /**
30
-     * Tells whether the content type is valid.
31
-     *
32
-     * @return bool
33
-     */
34
-    public function hasValidContentType()
35
-    {
36
-        return isset($GLOBALS['_SERVER']['CONTENT_TYPE']);
37
-    }
29
+	/**
30
+	 * Tells whether the content type is valid.
31
+	 *
32
+	 * @return bool
33
+	 */
34
+	public function hasValidContentType()
35
+	{
36
+		return isset($GLOBALS['_SERVER']['CONTENT_TYPE']);
37
+	}
38 38
 
39
-    /**
40
-     * Tells whether the form is multiparted, e.g "multipart/form-data"
41
-     *
42
-     * @return bool
43
-     */
44
-    public function isMultiparted()
45
-    {
46
-        return strpos(strtolower($GLOBALS['_SERVER']['CONTENT_TYPE']), 'multipart/form-data') === 0;
47
-    }
39
+	/**
40
+	 * Tells whether the form is multiparted, e.g "multipart/form-data"
41
+	 *
42
+	 * @return bool
43
+	 */
44
+	public function isMultiparted()
45
+	{
46
+		return strpos(strtolower($GLOBALS['_SERVER']['CONTENT_TYPE']), 'multipart/form-data') === 0;
47
+	}
48 48
 
49
-    /**
50
-     * Tells whether the form is URL encoded, e.g "application/x-www-form-urlencoded; charset=UTF-8"
51
-     *
52
-     * @return bool
53
-     */
54
-    public function isUrlEncoded()
55
-    {
56
-        return strpos(strtolower($GLOBALS['_SERVER']['CONTENT_TYPE']), 'application/x-www-form-urlencoded') === 0;
57
-    }
49
+	/**
50
+	 * Tells whether the form is URL encoded, e.g "application/x-www-form-urlencoded; charset=UTF-8"
51
+	 *
52
+	 * @return bool
53
+	 */
54
+	public function isUrlEncoded()
55
+	{
56
+		return strpos(strtolower($GLOBALS['_SERVER']['CONTENT_TYPE']), 'application/x-www-form-urlencoded') === 0;
57
+	}
58 58
 
59
-    /**
60
-     * Tells whether the form is octet streamed, e.g "application/x-www-form-urlencoded; charset=UTF-8"
61
-     *
62
-     * @return bool
63
-     */
64
-    public function isOctetStreamed()
65
-    {
66
-        return strpos(strtolower($GLOBALS['_SERVER']['CONTENT_TYPE']), 'application/octet-stream') === 0;
67
-    }
59
+	/**
60
+	 * Tells whether the form is octet streamed, e.g "application/x-www-form-urlencoded; charset=UTF-8"
61
+	 *
62
+	 * @return bool
63
+	 */
64
+	public function isOctetStreamed()
65
+	{
66
+		return strpos(strtolower($GLOBALS['_SERVER']['CONTENT_TYPE']), 'application/octet-stream') === 0;
67
+	}
68 68
 
69 69
 }
Please login to merge, or discard this patch.
Classes/Tool/CacheWarmUpTool.php 1 patch
Indentation   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -16,73 +16,73 @@
 block discarded – undo
16 16
 class CacheWarmUpTool extends AbstractTool
17 17
 {
18 18
 
19
-    /**
20
-     * Display the title of the tool on the welcome screen.
21
-     *
22
-     * @return string
23
-     */
24
-    public function getTitle()
25
-    {
26
-        return 'Cache warm up';
27
-    }
19
+	/**
20
+	 * Display the title of the tool on the welcome screen.
21
+	 *
22
+	 * @return string
23
+	 */
24
+	public function getTitle()
25
+	{
26
+		return 'Cache warm up';
27
+	}
28 28
 
29
-    /**
30
-     * Display the description of the tool in the welcome screen.
31
-     *
32
-     * @return string
33
-     */
34
-    public function getDescription()
35
-    {
36
-        $templateNameAndPath = 'EXT:media/Resources/Private/Standalone/Tool/CacheWarmUp/Launcher.html';
37
-        $view = $this->initializeStandaloneView($templateNameAndPath);
38
-        $view->assign('sitePath', PATH_site);
39
-        return $view->render();
40
-    }
29
+	/**
30
+	 * Display the description of the tool in the welcome screen.
31
+	 *
32
+	 * @return string
33
+	 */
34
+	public function getDescription()
35
+	{
36
+		$templateNameAndPath = 'EXT:media/Resources/Private/Standalone/Tool/CacheWarmUp/Launcher.html';
37
+		$view = $this->initializeStandaloneView($templateNameAndPath);
38
+		$view->assign('sitePath', PATH_site);
39
+		return $view->render();
40
+	}
41 41
 
42
-    /**
43
-     * Do the job: warm up the cache.
44
-     *
45
-     * @param array $arguments
46
-     * @return string
47
-     */
48
-    public function work(array $arguments = [])
49
-    {
42
+	/**
43
+	 * Do the job: warm up the cache.
44
+	 *
45
+	 * @param array $arguments
46
+	 * @return string
47
+	 */
48
+	public function work(array $arguments = [])
49
+	{
50 50
 
51
-        $templateNameAndPath = 'EXT:media/Resources/Private/Standalone/Tool/CacheWarmUp/WorkResult.html';
52
-        $view = $this->initializeStandaloneView($templateNameAndPath);
51
+		$templateNameAndPath = 'EXT:media/Resources/Private/Standalone/Tool/CacheWarmUp/WorkResult.html';
52
+		$view = $this->initializeStandaloneView($templateNameAndPath);
53 53
 
54
-        $numberOfEntries = $this->getCacheService()->warmUp();
55
-        $view->assign('numberOfEntries', $numberOfEntries);
56
-        touch($this->getWarmUpSemaphorFile());
54
+		$numberOfEntries = $this->getCacheService()->warmUp();
55
+		$view->assign('numberOfEntries', $numberOfEntries);
56
+		touch($this->getWarmUpSemaphorFile());
57 57
 
58
-        return $view->render();
59
-    }
58
+		return $view->render();
59
+	}
60 60
 
61
-    /**
62
-     * Tell whether the tools should be displayed according to the context.
63
-     *
64
-     * @return bool
65
-     */
66
-    public function isShown()
67
-    {
68
-        return $this->getBackendUser()->isAdmin();
69
-    }
61
+	/**
62
+	 * Tell whether the tools should be displayed according to the context.
63
+	 *
64
+	 * @return bool
65
+	 */
66
+	public function isShown()
67
+	{
68
+		return $this->getBackendUser()->isAdmin();
69
+	}
70 70
 
71
-    /**
72
-     * @return string
73
-     */
74
-    protected function getWarmUpSemaphorFile()
75
-    {
76
-        return PATH_site . 'typo3temp/.media_cache_warmed_up';
77
-    }
71
+	/**
72
+	 * @return string
73
+	 */
74
+	protected function getWarmUpSemaphorFile()
75
+	{
76
+		return PATH_site . 'typo3temp/.media_cache_warmed_up';
77
+	}
78 78
 
79
-    /**
80
-     * @return \Fab\Media\Cache\CacheService|object
81
-     */
82
-    protected function getCacheService()
83
-    {
84
-        return GeneralUtility::makeInstance(\Fab\Media\Cache\CacheService::class);
85
-    }
79
+	/**
80
+	 * @return \Fab\Media\Cache\CacheService|object
81
+	 */
82
+	protected function getCacheService()
83
+	{
84
+		return GeneralUtility::makeInstance(\Fab\Media\Cache\CacheService::class);
85
+	}
86 86
 
87 87
 }
88 88
 
Please login to merge, or discard this patch.