Completed
Push — master ( 02a2d0...8117b3 )
by Fabien
54:58
created
Classes/Tool/DuplicateRecordsFinderTool.php 1 patch
Indentation   +80 added lines, -80 removed lines patch added patch discarded remove patch
@@ -20,86 +20,86 @@
 block discarded – undo
20 20
 class DuplicateRecordsFinderTool extends AbstractTool
21 21
 {
22 22
 
23
-    /**
24
-     * Display the title of the tool on the welcome screen.
25
-     *
26
-     * @return string
27
-     */
28
-    public function getTitle()
29
-    {
30
-        return 'Find duplicate Records';
31
-    }
32
-
33
-    /**
34
-     * Display the description of the tool in the welcome screen.
35
-     *
36
-     * @return string
37
-     */
38
-    public function getDescription()
39
-    {
40
-        $templateNameAndPath = 'EXT:media/Resources/Private/Standalone/Tool/DuplicateRecordsFinder/Launcher.html';
41
-        $view = $this->initializeStandaloneView($templateNameAndPath);
42
-        $view->assign('sitePath', Environment::getPublicPath() . '/');
43
-        return $view->render();
44
-    }
45
-
46
-    /**
47
-     * Do the job: analyse Index.
48
-     *
49
-     * @param array $arguments
50
-     * @return string
51
-     */
52
-    public function work(array $arguments = [])
53
-    {
54
-
55
-        $templateNameAndPath = 'EXT:media/Resources/Private/Standalone/Tool/DuplicateRecordsFinder/WorkResult.html';
56
-        $view = $this->initializeStandaloneView($templateNameAndPath);
57
-
58
-        $duplicateRecordsReports = [];
59
-        foreach ($this->getStorageRepository()->findAll() as $storage) {
60
-
61
-            if ($storage->isOnline()) {
62
-                $duplicateFiles = $this->getIndexAnalyser()->searchForDuplicateIdentifiers($storage);
63
-                $duplicateRecordsReports[] = array(
64
-                    'storage' => $storage,
65
-                    'duplicateFiles' => $duplicateFiles,
66
-                    'numberOfDuplicateFiles' => count($duplicateFiles),
67
-                );
68
-            }
69
-        }
70
-
71
-        $view->assign('duplicateRecordsReports', $duplicateRecordsReports);
72
-
73
-        return $view->render();
74
-    }
75
-
76
-    /**
77
-     * Return a pointer to the database.
78
-     *
79
-     * @return \Fab\Media\Index\IndexAnalyser|object
80
-     */
81
-    protected function getIndexAnalyser()
82
-    {
83
-        return GeneralUtility::makeInstance(\Fab\Media\Index\IndexAnalyser::class);
84
-    }
85
-
86
-    /**
87
-     * @return StorageRepository|object
88
-     */
89
-    protected function getStorageRepository()
90
-    {
91
-        return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class);
92
-    }
93
-
94
-    /**
95
-     * Tell whether the tools should be displayed according to the context.
96
-     *
97
-     * @return bool
98
-     */
99
-    public function isShown()
100
-    {
101
-        return $this->getBackendUser()->isAdmin();
102
-    }
23
+	/**
24
+	 * Display the title of the tool on the welcome screen.
25
+	 *
26
+	 * @return string
27
+	 */
28
+	public function getTitle()
29
+	{
30
+		return 'Find duplicate Records';
31
+	}
32
+
33
+	/**
34
+	 * Display the description of the tool in the welcome screen.
35
+	 *
36
+	 * @return string
37
+	 */
38
+	public function getDescription()
39
+	{
40
+		$templateNameAndPath = 'EXT:media/Resources/Private/Standalone/Tool/DuplicateRecordsFinder/Launcher.html';
41
+		$view = $this->initializeStandaloneView($templateNameAndPath);
42
+		$view->assign('sitePath', Environment::getPublicPath() . '/');
43
+		return $view->render();
44
+	}
45
+
46
+	/**
47
+	 * Do the job: analyse Index.
48
+	 *
49
+	 * @param array $arguments
50
+	 * @return string
51
+	 */
52
+	public function work(array $arguments = [])
53
+	{
54
+
55
+		$templateNameAndPath = 'EXT:media/Resources/Private/Standalone/Tool/DuplicateRecordsFinder/WorkResult.html';
56
+		$view = $this->initializeStandaloneView($templateNameAndPath);
57
+
58
+		$duplicateRecordsReports = [];
59
+		foreach ($this->getStorageRepository()->findAll() as $storage) {
60
+
61
+			if ($storage->isOnline()) {
62
+				$duplicateFiles = $this->getIndexAnalyser()->searchForDuplicateIdentifiers($storage);
63
+				$duplicateRecordsReports[] = array(
64
+					'storage' => $storage,
65
+					'duplicateFiles' => $duplicateFiles,
66
+					'numberOfDuplicateFiles' => count($duplicateFiles),
67
+				);
68
+			}
69
+		}
70
+
71
+		$view->assign('duplicateRecordsReports', $duplicateRecordsReports);
72
+
73
+		return $view->render();
74
+	}
75
+
76
+	/**
77
+	 * Return a pointer to the database.
78
+	 *
79
+	 * @return \Fab\Media\Index\IndexAnalyser|object
80
+	 */
81
+	protected function getIndexAnalyser()
82
+	{
83
+		return GeneralUtility::makeInstance(\Fab\Media\Index\IndexAnalyser::class);
84
+	}
85
+
86
+	/**
87
+	 * @return StorageRepository|object
88
+	 */
89
+	protected function getStorageRepository()
90
+	{
91
+		return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class);
92
+	}
93
+
94
+	/**
95
+	 * Tell whether the tools should be displayed according to the context.
96
+	 *
97
+	 * @return bool
98
+	 */
99
+	public function isShown()
100
+	{
101
+		return $this->getBackendUser()->isAdmin();
102
+	}
103 103
 
104 104
 }
105 105
 
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
@@ -21,362 +21,362 @@
 block discarded – undo
21 21
 class UploadManager
22 22
 {
23 23
 
24
-    const UPLOAD_FOLDER = 'typo3temp/pics';
25
-
26
-    /**
27
-     * @var int|null|string
28
-     */
29
-    protected $sizeLimit;
30
-
31
-    /**
32
-     * @var string
33
-     */
34
-    protected $uploadFolder;
35
-
36
-    /**
37
-     * @var FormUtility
38
-     */
39
-    protected $formUtility;
40
-
41
-    /**
42
-     * @var \TYPO3\CMS\Core\Resource\ResourceStorage
43
-     */
44
-    protected $storage;
45
-
46
-    /**
47
-     * Name of the file input in the DOM.
48
-     *
49
-     * @var string
50
-     */
51
-    protected $inputName = 'qqfile';
52
-
53
-    /**
54
-     * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storage
55
-     * @return UploadManager
56
-     */
57
-    function __construct($storage = null)
58
-    {
59
-
60
-        $this->initializeUploadFolder();
61
-
62
-        // max file size in bytes
63
-        $this->sizeLimit = GeneralUtility::getMaxUploadFileSize() * 1024;
64
-        $this->checkServerSettings();
65
-
66
-        $this->formUtility = FormUtility::getInstance();
67
-        $this->storage = $storage;
68
-    }
69
-
70
-    /**
71
-     * Handle the uploaded file.
72
-     *
73
-     * @return UploadedFileInterface
74
-     */
75
-    public function handleUpload()
76
-    {
77
-
78
-        /** @var $uploadedFile UploadedFileInterface */
79
-        $uploadedFile = false;
80
-        if ($this->formUtility->isMultiparted()) {
81
-
82
-            // Default case
83
-            $uploadedFile = GeneralUtility::makeInstance(\Fab\Media\FileUpload\MultipartedFile::class);
84
-        } elseif ($this->formUtility->isOctetStreamed()) {
85
-
86
-            // Fine Upload plugin would use it if forceEncoded = false and paramsInBody = false
87
-            $uploadedFile = GeneralUtility::makeInstance(\Fab\Media\FileUpload\StreamedFile::class);
88
-        } elseif ($this->formUtility->isUrlEncoded()) {
89
-
90
-            // Used for image resizing in BE
91
-            $uploadedFile = GeneralUtility::makeInstance(\Fab\Media\FileUpload\Base64File::class);
92
-        }
93
-
94
-        if (!$uploadedFile) {
95
-            $this->throwException('Could not instantiate an upload object... No file was uploaded?');
96
-        }
97
-
98
-        $fileName = $this->getFileName($uploadedFile);
99
-
100
-        $this->checkFileSize($uploadedFile->getSize());
101
-        $this->checkFileAllowed($fileName);
102
-
103
-        $saved = $uploadedFile->setInputName($this->inputName)
104
-            ->setUploadFolder($this->uploadFolder)
105
-            ->setName($fileName)
106
-            ->save();
107
-
108
-        if (!$saved) {
109
-            $this->throwException('Could not save uploaded file. The upload was cancelled, or server error encountered');
110
-        }
111
-
112
-        // Optimize file if the uploaded file is an image.
113
-        if ($uploadedFile->getType() == \TYPO3\CMS\Core\Resource\File::FILETYPE_IMAGE) {
114
-            $uploadedFile = ImageOptimizer::getInstance($this->storage)->optimize($uploadedFile);
115
-        }
116
-        return $uploadedFile;
117
-    }
118
-
119
-    /**
120
-     * Internal function that checks if server's may sizes match the
121
-     * object's maximum size for uploads.
122
-     *
123
-     * @return void
124
-     */
125
-    protected function checkServerSettings()
126
-    {
127
-        $postSize = $this->toBytes(ini_get('post_max_size'));
128
-
129
-        $uploadSize = $this->toBytes(ini_get('upload_max_filesize'));
130
-
131
-        if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit) {
132
-            $size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';
133
-            $this->throwException('increase post_max_size and upload_max_filesize to ' . $size);
134
-        }
135
-    }
136
-
137
-    /**
138
-     * Convert a given size with units to bytes.
139
-     *
140
-     * @param string $str
141
-     * @return int|string
142
-     */
143
-    protected function toBytes($str)
144
-    {
145
-        $val = trim($str);
146
-        $last = strtolower($str[strlen($str) - 1]);
147
-        switch ($last) {
148
-            case 'g':
149
-                $val *= 1024;
150
-            case 'm':
151
-                $val *= 1024;
152
-            case 'k':
153
-                $val *= 1024;
154
-        }
155
-        return $val;
156
-    }
157
-
158
-    /**
159
-     * Return a file name given an uploaded file
160
-     *
161
-     * @param UploadedFileInterface $uploadedFile
162
-     * @return string
163
-     */
164
-    public function getFileName(UploadedFileInterface $uploadedFile)
165
-    {
166
-        $pathInfo = pathinfo($uploadedFile->getOriginalName());
167
-        $fileName = $this->sanitizeFileName($pathInfo['filename']);
168
-        $fileNameWithExtension = $fileName;
169
-        if (!empty($pathInfo['extension'])) {
170
-            $fileNameWithExtension = sprintf('%s.%s', $fileName, $pathInfo['extension']);
171
-        }
172
-        return $fileNameWithExtension;
173
-    }
174
-
175
-    /**
176
-     * Check whether the file size does not exceed the allowed limit
177
-     *
178
-     * @param int $size
179
-     */
180
-    public function checkFileSize($size)
181
-    {
182
-        if ($size == 0) {
183
-            $this->throwException('File is empty');
184
-        }
185
-
186
-        if ($size > $this->sizeLimit) {
187
-            $this->throwException('File is too large');
188
-        }
189
-    }
190
-
191
-    /**
192
-     * Check whether the file is allowed
193
-     *
194
-     * @param string $fileName
195
-     */
196
-    public function checkFileAllowed($fileName)
197
-    {
198
-        $isAllowed = $this->checkFileExtensionPermission($fileName);
199
-        if (!$isAllowed) {
200
-            $these = PermissionUtility::getInstance()->getAllowedExtensionList();
201
-            $this->throwException('File has an invalid extension, it should be one of ' . $these . '.');
202
-        }
203
-    }
204
-
205
-    /**
206
-     * If the fileName is given, check it against the
207
-     * TYPO3_CONF_VARS[BE][fileDenyPattern] + and if the file extension is allowed
208
-     *
209
-     * @see \TYPO3\CMS\Core\Resource\ResourceStorage->checkFileExtensionPermission($fileName);
210
-     * @param string $fileName Full filename
211
-     * @return boolean true if extension/filename is allowed
212
-     */
213
-    public function checkFileExtensionPermission($fileName)
214
-    {
215
-        $isAllowed = GeneralUtility::verifyFilenameAgainstDenyPattern($fileName);
216
-        if ($isAllowed) {
217
-            $fileInfo = GeneralUtility::split_fileref($fileName);
218
-            // Set up the permissions for the file extension
219
-            $fileExtensionPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']['webspace'];
220
-            $fileExtensionPermissions['allow'] = GeneralUtility::uniqueList(strtolower($fileExtensionPermissions['allow']));
221
-            $fileExtensionPermissions['deny'] = GeneralUtility::uniqueList(strtolower($fileExtensionPermissions['deny']));
222
-            $fileExtension = strtolower($fileInfo['fileext']);
223
-            if ($fileExtension !== '') {
224
-                // If the extension is found amongst the allowed types, we return true immediately
225
-                if ($fileExtensionPermissions['allow'] === '*' || GeneralUtility::inList($fileExtensionPermissions['allow'], $fileExtension)) {
226
-                    return true;
227
-                }
228
-                // If the extension is found amongst the denied types, we return false immediately
229
-                if ($fileExtensionPermissions['deny'] === '*' || GeneralUtility::inList($fileExtensionPermissions['deny'], $fileExtension)) {
230
-                    return false;
231
-                }
232
-                // If no match we return true
233
-                return true;
234
-            } else {
235
-                if ($fileExtensionPermissions['allow'] === '*') {
236
-                    return true;
237
-                }
238
-                if ($fileExtensionPermissions['deny'] === '*') {
239
-                    return false;
240
-                }
241
-                return true;
242
-            }
243
-        }
244
-        return false;
245
-    }
246
-
247
-    /**
248
-     * Sanitize the file name for the web.
249
-     * It has been noticed issues when letting done this work by FAL. Give it a little hand.
250
-     *
251
-     * @see https://github.com/alixaxel/phunction/blob/master/phunction/Text.php#L252
252
-     * @param string $fileName
253
-     * @param string $slug
254
-     * @param string $extra
255
-     * @return string
256
-     */
257
-    public function sanitizeFileName($fileName, $slug = '-', $extra = null)
258
-    {
259
-        return trim(preg_replace('~[^0-9a-z_' . preg_quote($extra, '~') . ']+~i', $slug, $this->unAccent($fileName)), $slug);
260
-    }
261
-
262
-    /**
263
-     * Remove accent from a string
264
-     *
265
-     * @see https://github.com/alixaxel/phunction/blob/master/phunction/Text.php#L297
266
-     * @param $string
267
-     * @return string
268
-     */
269
-    protected function unAccent($string)
270
-    {
271
-        $searches = array('ç', 'æ', 'œ', 'á', 'é', 'í', 'ó', 'ú', 'à', 'è', 'ì', 'ò', 'ù', 'ä', 'ë', 'ï', 'ö', 'ü', 'ÿ', 'â', 'ê', 'î', 'ô', 'û', 'å', 'e', 'i', 'ø', 'u');
272
-        $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');
273
-        $sanitizedString = str_replace($searches, $replaces, $string);
274
-
275
-        if (extension_loaded('intl') === true) {
276
-            $sanitizedString = \Normalizer::normalize($sanitizedString, \Normalizer::FORM_KD);
277
-        }
278
-        return $sanitizedString;
279
-    }
280
-
281
-    /**
282
-     * @throws FailedFileUploadException
283
-     * @param string $message
284
-     */
285
-    protected function throwException($message)
286
-    {
287
-        throw new FailedFileUploadException($message, 1357510420);
288
-    }
289
-
290
-    /**
291
-     * Initialize Upload Folder.
292
-     *
293
-     * @return void
294
-     */
295
-    protected function initializeUploadFolder()
296
-    {
297
-        $this->uploadFolder = Environment::getPublicPath() . '/' . self::UPLOAD_FOLDER;
298
-
299
-        // Initialize the upload folder for file transfer and create it if not yet existing
300
-        if (!file_exists($this->uploadFolder)) {
301
-            GeneralUtility::mkdir($this->uploadFolder);
302
-        }
303
-
304
-        // Check whether the upload folder is writable
305
-        if (!is_writable($this->uploadFolder)) {
306
-            $this->throwException("Server error. Upload directory isn't writable.");
307
-        }
308
-    }
309
-
310
-    /**
311
-     * @return int|null|string
312
-     */
313
-    public function getSizeLimit()
314
-    {
315
-        return $this->sizeLimit;
316
-    }
317
-
318
-    /**
319
-     * @param int|null|string $sizeLimit
320
-     * @return $this
321
-     */
322
-    public function setSizeLimit($sizeLimit)
323
-    {
324
-        $this->sizeLimit = $sizeLimit;
325
-        return $this;
326
-    }
327
-
328
-    /**
329
-     * @return string
330
-     */
331
-    public function getUploadFolder()
332
-    {
333
-        return $this->uploadFolder;
334
-    }
335
-
336
-    /**
337
-     * @param string $uploadFolder
338
-     * @return $this
339
-     */
340
-    public function setUploadFolder($uploadFolder)
341
-    {
342
-        $this->uploadFolder = $uploadFolder;
343
-        return $this;
344
-    }
345
-
346
-    /**
347
-     * @return string
348
-     */
349
-    public function getInputName()
350
-    {
351
-        return $this->inputName;
352
-    }
353
-
354
-    /**
355
-     * @param string $inputName
356
-     * @return $this
357
-     */
358
-    public function setInputName($inputName)
359
-    {
360
-        $this->inputName = $inputName;
361
-        return $this;
362
-    }
363
-
364
-    /**
365
-     * @return \TYPO3\CMS\Core\Resource\ResourceStorage
366
-     */
367
-    public function getStorage()
368
-    {
369
-        return $this->storage;
370
-    }
371
-
372
-    /**
373
-     * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storage
374
-     * @return $this
375
-     */
376
-    public function setStorage($storage)
377
-    {
378
-        $this->storage = $storage;
379
-        return $this;
380
-    }
24
+	const UPLOAD_FOLDER = 'typo3temp/pics';
25
+
26
+	/**
27
+	 * @var int|null|string
28
+	 */
29
+	protected $sizeLimit;
30
+
31
+	/**
32
+	 * @var string
33
+	 */
34
+	protected $uploadFolder;
35
+
36
+	/**
37
+	 * @var FormUtility
38
+	 */
39
+	protected $formUtility;
40
+
41
+	/**
42
+	 * @var \TYPO3\CMS\Core\Resource\ResourceStorage
43
+	 */
44
+	protected $storage;
45
+
46
+	/**
47
+	 * Name of the file input in the DOM.
48
+	 *
49
+	 * @var string
50
+	 */
51
+	protected $inputName = 'qqfile';
52
+
53
+	/**
54
+	 * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storage
55
+	 * @return UploadManager
56
+	 */
57
+	function __construct($storage = null)
58
+	{
59
+
60
+		$this->initializeUploadFolder();
61
+
62
+		// max file size in bytes
63
+		$this->sizeLimit = GeneralUtility::getMaxUploadFileSize() * 1024;
64
+		$this->checkServerSettings();
65
+
66
+		$this->formUtility = FormUtility::getInstance();
67
+		$this->storage = $storage;
68
+	}
69
+
70
+	/**
71
+	 * Handle the uploaded file.
72
+	 *
73
+	 * @return UploadedFileInterface
74
+	 */
75
+	public function handleUpload()
76
+	{
77
+
78
+		/** @var $uploadedFile UploadedFileInterface */
79
+		$uploadedFile = false;
80
+		if ($this->formUtility->isMultiparted()) {
81
+
82
+			// Default case
83
+			$uploadedFile = GeneralUtility::makeInstance(\Fab\Media\FileUpload\MultipartedFile::class);
84
+		} elseif ($this->formUtility->isOctetStreamed()) {
85
+
86
+			// Fine Upload plugin would use it if forceEncoded = false and paramsInBody = false
87
+			$uploadedFile = GeneralUtility::makeInstance(\Fab\Media\FileUpload\StreamedFile::class);
88
+		} elseif ($this->formUtility->isUrlEncoded()) {
89
+
90
+			// Used for image resizing in BE
91
+			$uploadedFile = GeneralUtility::makeInstance(\Fab\Media\FileUpload\Base64File::class);
92
+		}
93
+
94
+		if (!$uploadedFile) {
95
+			$this->throwException('Could not instantiate an upload object... No file was uploaded?');
96
+		}
97
+
98
+		$fileName = $this->getFileName($uploadedFile);
99
+
100
+		$this->checkFileSize($uploadedFile->getSize());
101
+		$this->checkFileAllowed($fileName);
102
+
103
+		$saved = $uploadedFile->setInputName($this->inputName)
104
+			->setUploadFolder($this->uploadFolder)
105
+			->setName($fileName)
106
+			->save();
107
+
108
+		if (!$saved) {
109
+			$this->throwException('Could not save uploaded file. The upload was cancelled, or server error encountered');
110
+		}
111
+
112
+		// Optimize file if the uploaded file is an image.
113
+		if ($uploadedFile->getType() == \TYPO3\CMS\Core\Resource\File::FILETYPE_IMAGE) {
114
+			$uploadedFile = ImageOptimizer::getInstance($this->storage)->optimize($uploadedFile);
115
+		}
116
+		return $uploadedFile;
117
+	}
118
+
119
+	/**
120
+	 * Internal function that checks if server's may sizes match the
121
+	 * object's maximum size for uploads.
122
+	 *
123
+	 * @return void
124
+	 */
125
+	protected function checkServerSettings()
126
+	{
127
+		$postSize = $this->toBytes(ini_get('post_max_size'));
128
+
129
+		$uploadSize = $this->toBytes(ini_get('upload_max_filesize'));
130
+
131
+		if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit) {
132
+			$size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';
133
+			$this->throwException('increase post_max_size and upload_max_filesize to ' . $size);
134
+		}
135
+	}
136
+
137
+	/**
138
+	 * Convert a given size with units to bytes.
139
+	 *
140
+	 * @param string $str
141
+	 * @return int|string
142
+	 */
143
+	protected function toBytes($str)
144
+	{
145
+		$val = trim($str);
146
+		$last = strtolower($str[strlen($str) - 1]);
147
+		switch ($last) {
148
+			case 'g':
149
+				$val *= 1024;
150
+			case 'm':
151
+				$val *= 1024;
152
+			case 'k':
153
+				$val *= 1024;
154
+		}
155
+		return $val;
156
+	}
157
+
158
+	/**
159
+	 * Return a file name given an uploaded file
160
+	 *
161
+	 * @param UploadedFileInterface $uploadedFile
162
+	 * @return string
163
+	 */
164
+	public function getFileName(UploadedFileInterface $uploadedFile)
165
+	{
166
+		$pathInfo = pathinfo($uploadedFile->getOriginalName());
167
+		$fileName = $this->sanitizeFileName($pathInfo['filename']);
168
+		$fileNameWithExtension = $fileName;
169
+		if (!empty($pathInfo['extension'])) {
170
+			$fileNameWithExtension = sprintf('%s.%s', $fileName, $pathInfo['extension']);
171
+		}
172
+		return $fileNameWithExtension;
173
+	}
174
+
175
+	/**
176
+	 * Check whether the file size does not exceed the allowed limit
177
+	 *
178
+	 * @param int $size
179
+	 */
180
+	public function checkFileSize($size)
181
+	{
182
+		if ($size == 0) {
183
+			$this->throwException('File is empty');
184
+		}
185
+
186
+		if ($size > $this->sizeLimit) {
187
+			$this->throwException('File is too large');
188
+		}
189
+	}
190
+
191
+	/**
192
+	 * Check whether the file is allowed
193
+	 *
194
+	 * @param string $fileName
195
+	 */
196
+	public function checkFileAllowed($fileName)
197
+	{
198
+		$isAllowed = $this->checkFileExtensionPermission($fileName);
199
+		if (!$isAllowed) {
200
+			$these = PermissionUtility::getInstance()->getAllowedExtensionList();
201
+			$this->throwException('File has an invalid extension, it should be one of ' . $these . '.');
202
+		}
203
+	}
204
+
205
+	/**
206
+	 * If the fileName is given, check it against the
207
+	 * TYPO3_CONF_VARS[BE][fileDenyPattern] + and if the file extension is allowed
208
+	 *
209
+	 * @see \TYPO3\CMS\Core\Resource\ResourceStorage->checkFileExtensionPermission($fileName);
210
+	 * @param string $fileName Full filename
211
+	 * @return boolean true if extension/filename is allowed
212
+	 */
213
+	public function checkFileExtensionPermission($fileName)
214
+	{
215
+		$isAllowed = GeneralUtility::verifyFilenameAgainstDenyPattern($fileName);
216
+		if ($isAllowed) {
217
+			$fileInfo = GeneralUtility::split_fileref($fileName);
218
+			// Set up the permissions for the file extension
219
+			$fileExtensionPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']['webspace'];
220
+			$fileExtensionPermissions['allow'] = GeneralUtility::uniqueList(strtolower($fileExtensionPermissions['allow']));
221
+			$fileExtensionPermissions['deny'] = GeneralUtility::uniqueList(strtolower($fileExtensionPermissions['deny']));
222
+			$fileExtension = strtolower($fileInfo['fileext']);
223
+			if ($fileExtension !== '') {
224
+				// If the extension is found amongst the allowed types, we return true immediately
225
+				if ($fileExtensionPermissions['allow'] === '*' || GeneralUtility::inList($fileExtensionPermissions['allow'], $fileExtension)) {
226
+					return true;
227
+				}
228
+				// If the extension is found amongst the denied types, we return false immediately
229
+				if ($fileExtensionPermissions['deny'] === '*' || GeneralUtility::inList($fileExtensionPermissions['deny'], $fileExtension)) {
230
+					return false;
231
+				}
232
+				// If no match we return true
233
+				return true;
234
+			} else {
235
+				if ($fileExtensionPermissions['allow'] === '*') {
236
+					return true;
237
+				}
238
+				if ($fileExtensionPermissions['deny'] === '*') {
239
+					return false;
240
+				}
241
+				return true;
242
+			}
243
+		}
244
+		return false;
245
+	}
246
+
247
+	/**
248
+	 * Sanitize the file name for the web.
249
+	 * It has been noticed issues when letting done this work by FAL. Give it a little hand.
250
+	 *
251
+	 * @see https://github.com/alixaxel/phunction/blob/master/phunction/Text.php#L252
252
+	 * @param string $fileName
253
+	 * @param string $slug
254
+	 * @param string $extra
255
+	 * @return string
256
+	 */
257
+	public function sanitizeFileName($fileName, $slug = '-', $extra = null)
258
+	{
259
+		return trim(preg_replace('~[^0-9a-z_' . preg_quote($extra, '~') . ']+~i', $slug, $this->unAccent($fileName)), $slug);
260
+	}
261
+
262
+	/**
263
+	 * Remove accent from a string
264
+	 *
265
+	 * @see https://github.com/alixaxel/phunction/blob/master/phunction/Text.php#L297
266
+	 * @param $string
267
+	 * @return string
268
+	 */
269
+	protected function unAccent($string)
270
+	{
271
+		$searches = array('ç', 'æ', 'œ', 'á', 'é', 'í', 'ó', 'ú', 'à', 'è', 'ì', 'ò', 'ù', 'ä', 'ë', 'ï', 'ö', 'ü', 'ÿ', 'â', 'ê', 'î', 'ô', 'û', 'å', 'e', 'i', 'ø', 'u');
272
+		$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');
273
+		$sanitizedString = str_replace($searches, $replaces, $string);
274
+
275
+		if (extension_loaded('intl') === true) {
276
+			$sanitizedString = \Normalizer::normalize($sanitizedString, \Normalizer::FORM_KD);
277
+		}
278
+		return $sanitizedString;
279
+	}
280
+
281
+	/**
282
+	 * @throws FailedFileUploadException
283
+	 * @param string $message
284
+	 */
285
+	protected function throwException($message)
286
+	{
287
+		throw new FailedFileUploadException($message, 1357510420);
288
+	}
289
+
290
+	/**
291
+	 * Initialize Upload Folder.
292
+	 *
293
+	 * @return void
294
+	 */
295
+	protected function initializeUploadFolder()
296
+	{
297
+		$this->uploadFolder = Environment::getPublicPath() . '/' . self::UPLOAD_FOLDER;
298
+
299
+		// Initialize the upload folder for file transfer and create it if not yet existing
300
+		if (!file_exists($this->uploadFolder)) {
301
+			GeneralUtility::mkdir($this->uploadFolder);
302
+		}
303
+
304
+		// Check whether the upload folder is writable
305
+		if (!is_writable($this->uploadFolder)) {
306
+			$this->throwException("Server error. Upload directory isn't writable.");
307
+		}
308
+	}
309
+
310
+	/**
311
+	 * @return int|null|string
312
+	 */
313
+	public function getSizeLimit()
314
+	{
315
+		return $this->sizeLimit;
316
+	}
317
+
318
+	/**
319
+	 * @param int|null|string $sizeLimit
320
+	 * @return $this
321
+	 */
322
+	public function setSizeLimit($sizeLimit)
323
+	{
324
+		$this->sizeLimit = $sizeLimit;
325
+		return $this;
326
+	}
327
+
328
+	/**
329
+	 * @return string
330
+	 */
331
+	public function getUploadFolder()
332
+	{
333
+		return $this->uploadFolder;
334
+	}
335
+
336
+	/**
337
+	 * @param string $uploadFolder
338
+	 * @return $this
339
+	 */
340
+	public function setUploadFolder($uploadFolder)
341
+	{
342
+		$this->uploadFolder = $uploadFolder;
343
+		return $this;
344
+	}
345
+
346
+	/**
347
+	 * @return string
348
+	 */
349
+	public function getInputName()
350
+	{
351
+		return $this->inputName;
352
+	}
353
+
354
+	/**
355
+	 * @param string $inputName
356
+	 * @return $this
357
+	 */
358
+	public function setInputName($inputName)
359
+	{
360
+		$this->inputName = $inputName;
361
+		return $this;
362
+	}
363
+
364
+	/**
365
+	 * @return \TYPO3\CMS\Core\Resource\ResourceStorage
366
+	 */
367
+	public function getStorage()
368
+	{
369
+		return $this->storage;
370
+	}
371
+
372
+	/**
373
+	 * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storage
374
+	 * @return $this
375
+	 */
376
+	public function setStorage($storage)
377
+	{
378
+		$this->storage = $storage;
379
+		return $this;
380
+	}
381 381
 
382 382
 }
Please login to merge, or discard this patch.
Classes/FileUpload/UploadedFileAbstract.php 1 patch
Indentation   +137 added lines, -137 removed lines patch added patch discarded remove patch
@@ -19,142 +19,142 @@
 block discarded – undo
19 19
 abstract class UploadedFileAbstract implements UploadedFileInterface
20 20
 {
21 21
 
22
-    /**
23
-     * @var string
24
-     */
25
-    protected $uploadFolder;
26
-
27
-    /**
28
-     * @var string
29
-     */
30
-    protected $inputName;
31
-
32
-    /**
33
-     * @var string
34
-     */
35
-    protected $name;
36
-
37
-    /**
38
-     * Get the file type.
39
-     *
40
-     * @return int
41
-     */
42
-    public function getType()
43
-    {
44
-        $this->checkFileExistence();
45
-
46
-        // this basically extracts the mimetype and guess the filetype based
47
-        // on the first part of the mimetype works for 99% of all cases, and
48
-        // we don't need to make an SQL statement like EXT:media does currently
49
-        $mimeType = $this->getMimeType();
50
-        list($fileType) = explode('/', $mimeType);
51
-        switch (strtolower($fileType)) {
52
-            case 'text':
53
-                $type = File::FILETYPE_TEXT;
54
-                break;
55
-            case 'image':
56
-                $type = File::FILETYPE_IMAGE;
57
-                break;
58
-            case 'audio':
59
-                $type = File::FILETYPE_AUDIO;
60
-                break;
61
-            case 'video':
62
-                $type = File::FILETYPE_VIDEO;
63
-                break;
64
-            case 'application':
65
-            case 'software':
66
-                $type = File::FILETYPE_APPLICATION;
67
-                break;
68
-            default:
69
-                $type = File::FILETYPE_UNKNOWN;
70
-        }
71
-        return $type;
72
-    }
73
-
74
-    /**
75
-     * Get the file with its absolute path.
76
-     *
77
-     * @return string
78
-     */
79
-    public function getFileWithAbsolutePath()
80
-    {
81
-        return $this->uploadFolder . DIRECTORY_SEPARATOR . $this->name;
82
-    }
83
-
84
-    /**
85
-     * Get the file's public URL.
86
-     *
87
-     * @return string
88
-     */
89
-    public function getPublicUrl()
90
-    {
91
-        $fileNameAndPath = str_replace(Environment::getPublicPath() . '/', '', $this->getFileWithAbsolutePath());
92
-        return '/' . ltrim($fileNameAndPath, '/');
93
-    }
94
-
95
-    /**
96
-     * @return string
97
-     */
98
-    public function getInputName()
99
-    {
100
-        return $this->inputName;
101
-    }
102
-
103
-    /**
104
-     * @param string $inputName
105
-     * @return UploadedFileInterface
106
-     */
107
-    public function setInputName($inputName)
108
-    {
109
-        $this->inputName = $inputName;
110
-        return $this;
111
-    }
112
-
113
-    /**
114
-     * @return string
115
-     */
116
-    public function getUploadFolder()
117
-    {
118
-        return $this->uploadFolder;
119
-    }
120
-
121
-    /**
122
-     * @param string $uploadFolder
123
-     * @return UploadedFileInterface
124
-     */
125
-    public function setUploadFolder($uploadFolder)
126
-    {
127
-        $this->uploadFolder = $uploadFolder;
128
-        return $this;
129
-    }
130
-
131
-    /**
132
-     * @return string
133
-     */
134
-    public function getName()
135
-    {
136
-        return $this->name;
137
-    }
138
-
139
-    /**
140
-     * @param string $name
141
-     * @return UploadedFileInterface
142
-     */
143
-    public function setName($name)
144
-    {
145
-        $this->name = $name;
146
-        return $this;
147
-    }
148
-
149
-    /**
150
-     * Check whether the file exists.
151
-     */
152
-    protected function checkFileExistence()
153
-    {
154
-        if (!is_file($this->getFileWithAbsolutePath())) {
155
-            $message = sprintf('File not found at "%s". Did you save it?', $this->getFileWithAbsolutePath());
156
-            throw new MissingFileException($message, 1361786958);
157
-        }
158
-    }
22
+	/**
23
+	 * @var string
24
+	 */
25
+	protected $uploadFolder;
26
+
27
+	/**
28
+	 * @var string
29
+	 */
30
+	protected $inputName;
31
+
32
+	/**
33
+	 * @var string
34
+	 */
35
+	protected $name;
36
+
37
+	/**
38
+	 * Get the file type.
39
+	 *
40
+	 * @return int
41
+	 */
42
+	public function getType()
43
+	{
44
+		$this->checkFileExistence();
45
+
46
+		// this basically extracts the mimetype and guess the filetype based
47
+		// on the first part of the mimetype works for 99% of all cases, and
48
+		// we don't need to make an SQL statement like EXT:media does currently
49
+		$mimeType = $this->getMimeType();
50
+		list($fileType) = explode('/', $mimeType);
51
+		switch (strtolower($fileType)) {
52
+			case 'text':
53
+				$type = File::FILETYPE_TEXT;
54
+				break;
55
+			case 'image':
56
+				$type = File::FILETYPE_IMAGE;
57
+				break;
58
+			case 'audio':
59
+				$type = File::FILETYPE_AUDIO;
60
+				break;
61
+			case 'video':
62
+				$type = File::FILETYPE_VIDEO;
63
+				break;
64
+			case 'application':
65
+			case 'software':
66
+				$type = File::FILETYPE_APPLICATION;
67
+				break;
68
+			default:
69
+				$type = File::FILETYPE_UNKNOWN;
70
+		}
71
+		return $type;
72
+	}
73
+
74
+	/**
75
+	 * Get the file with its absolute path.
76
+	 *
77
+	 * @return string
78
+	 */
79
+	public function getFileWithAbsolutePath()
80
+	{
81
+		return $this->uploadFolder . DIRECTORY_SEPARATOR . $this->name;
82
+	}
83
+
84
+	/**
85
+	 * Get the file's public URL.
86
+	 *
87
+	 * @return string
88
+	 */
89
+	public function getPublicUrl()
90
+	{
91
+		$fileNameAndPath = str_replace(Environment::getPublicPath() . '/', '', $this->getFileWithAbsolutePath());
92
+		return '/' . ltrim($fileNameAndPath, '/');
93
+	}
94
+
95
+	/**
96
+	 * @return string
97
+	 */
98
+	public function getInputName()
99
+	{
100
+		return $this->inputName;
101
+	}
102
+
103
+	/**
104
+	 * @param string $inputName
105
+	 * @return UploadedFileInterface
106
+	 */
107
+	public function setInputName($inputName)
108
+	{
109
+		$this->inputName = $inputName;
110
+		return $this;
111
+	}
112
+
113
+	/**
114
+	 * @return string
115
+	 */
116
+	public function getUploadFolder()
117
+	{
118
+		return $this->uploadFolder;
119
+	}
120
+
121
+	/**
122
+	 * @param string $uploadFolder
123
+	 * @return UploadedFileInterface
124
+	 */
125
+	public function setUploadFolder($uploadFolder)
126
+	{
127
+		$this->uploadFolder = $uploadFolder;
128
+		return $this;
129
+	}
130
+
131
+	/**
132
+	 * @return string
133
+	 */
134
+	public function getName()
135
+	{
136
+		return $this->name;
137
+	}
138
+
139
+	/**
140
+	 * @param string $name
141
+	 * @return UploadedFileInterface
142
+	 */
143
+	public function setName($name)
144
+	{
145
+		$this->name = $name;
146
+		return $this;
147
+	}
148
+
149
+	/**
150
+	 * Check whether the file exists.
151
+	 */
152
+	protected function checkFileExistence()
153
+	{
154
+		if (!is_file($this->getFileWithAbsolutePath())) {
155
+			$message = sprintf('File not found at "%s". Did you save it?', $this->getFileWithAbsolutePath());
156
+			throw new MissingFileException($message, 1361786958);
157
+		}
158
+	}
159 159
 
160 160
 }
Please login to merge, or discard this patch.
Classes/Command/FileCacheCommandController.php 1 patch
Indentation   +100 added lines, -100 removed lines patch added patch discarded remove patch
@@ -25,105 +25,105 @@
 block discarded – undo
25 25
 class FileCacheCommandController extends CommandController
26 26
 {
27 27
 
28
-    /**
29
-     * Warm up the cache. Update some caching columns such as "number_of_references" to speed up the search.
30
-     *
31
-     * @return void
32
-     */
33
-    public function warmUpCommand()
34
-    {
35
-        $numberOfEntries = $this->getCacheService()->warmUp();
36
-        $message = sprintf('Done! Processed %s entries', $numberOfEntries);
37
-        $this->outputLine($message);
38
-    }
39
-
40
-    /**
41
-     * Flush all processed files to be used for debugging mainly.
42
-     *
43
-     * @return void
44
-     */
45
-    public function flushProcessedFilesCommand()
46
-    {
47
-
48
-        foreach ($this->getStorageRepository()->findAll() as $storage) {
49
-
50
-            // This only works for local driver
51
-            if ($storage->getDriverType() === 'Local') {
52
-
53
-                $this->outputLine();
54
-                $this->outputLine(sprintf('%s (%s)', $storage->getName(), $storage->getUid()));
55
-                $this->outputLine('--------------------------------------------');
56
-                $this->outputLine();
57
-
58
-                #$storage->getProcessingFolder()->delete(true); // will not work
59
-
60
-                // Well... not really FAL friendly but straightforward for Local drivers.
61
-                $processedDirectoryPath = Environment::getPublicPath() . '/' . $storage->getProcessingFolder()->getPublicUrl();
62
-                $fileIterator = new FilesystemIterator($processedDirectoryPath, FilesystemIterator::SKIP_DOTS);
63
-                $numberOfProcessedFiles = iterator_count($fileIterator);
64
-
65
-                GeneralUtility::rmdir($processedDirectoryPath, true);
66
-                GeneralUtility::mkdir($processedDirectoryPath); // recreate the directory.
67
-
68
-                $message = sprintf('Done! Removed %s processed file(s).', $numberOfProcessedFiles);
69
-                $this->outputLine($message);
70
-
71
-                $count = $this->getDataService()
72
-                    ->count(
73
-                        'sys_file_processedfile',
74
-                        [
75
-                            'storage' => $storage->getUid()
76
-                        ]
77
-                    );
78
-
79
-                // Remove the record as well.
80
-                $this->getDataService()->delete('sys_file_processedfile', ['storage' => $storage->getUid()]);
81
-
82
-                $message = sprintf('Done! Removed %s records from "sys_file_processedfile".', $count);
83
-                $this->outputLine($message);
84
-            }
85
-
86
-        }
87
-
88
-        // Remove possible remaining "sys_file_processedfile"
89
-        $this
90
-            ->getConnection('sys_file_processedfile')
91
-            ->query('TRUNCATE sys_file_processedfile');
92
-    }
93
-
94
-    /**
95
-     * @return \Fab\Media\Cache\CacheService|object
96
-     */
97
-    protected function getCacheService()
98
-    {
99
-        return GeneralUtility::makeInstance(\Fab\Media\Cache\CacheService::class);
100
-    }
101
-
102
-    /**
103
-     * @return StorageRepository|object
104
-     */
105
-    protected function getStorageRepository()
106
-    {
107
-        return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class);
108
-    }
109
-
110
-    /**
111
-     * @return object|DataService
112
-     */
113
-    protected function getDataService(): DataService
114
-    {
115
-        return GeneralUtility::makeInstance(DataService::class);
116
-    }
117
-
118
-    /**
119
-     * @param string $tableName
120
-     * @return object|Connection
121
-     */
122
-    protected function getConnection($tableName): Connection
123
-    {
124
-        /** @var ConnectionPool $connectionPool */
125
-        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
126
-        return $connectionPool->getConnectionForTable($tableName);
127
-    }
28
+	/**
29
+	 * Warm up the cache. Update some caching columns such as "number_of_references" to speed up the search.
30
+	 *
31
+	 * @return void
32
+	 */
33
+	public function warmUpCommand()
34
+	{
35
+		$numberOfEntries = $this->getCacheService()->warmUp();
36
+		$message = sprintf('Done! Processed %s entries', $numberOfEntries);
37
+		$this->outputLine($message);
38
+	}
39
+
40
+	/**
41
+	 * Flush all processed files to be used for debugging mainly.
42
+	 *
43
+	 * @return void
44
+	 */
45
+	public function flushProcessedFilesCommand()
46
+	{
47
+
48
+		foreach ($this->getStorageRepository()->findAll() as $storage) {
49
+
50
+			// This only works for local driver
51
+			if ($storage->getDriverType() === 'Local') {
52
+
53
+				$this->outputLine();
54
+				$this->outputLine(sprintf('%s (%s)', $storage->getName(), $storage->getUid()));
55
+				$this->outputLine('--------------------------------------------');
56
+				$this->outputLine();
57
+
58
+				#$storage->getProcessingFolder()->delete(true); // will not work
59
+
60
+				// Well... not really FAL friendly but straightforward for Local drivers.
61
+				$processedDirectoryPath = Environment::getPublicPath() . '/' . $storage->getProcessingFolder()->getPublicUrl();
62
+				$fileIterator = new FilesystemIterator($processedDirectoryPath, FilesystemIterator::SKIP_DOTS);
63
+				$numberOfProcessedFiles = iterator_count($fileIterator);
64
+
65
+				GeneralUtility::rmdir($processedDirectoryPath, true);
66
+				GeneralUtility::mkdir($processedDirectoryPath); // recreate the directory.
67
+
68
+				$message = sprintf('Done! Removed %s processed file(s).', $numberOfProcessedFiles);
69
+				$this->outputLine($message);
70
+
71
+				$count = $this->getDataService()
72
+					->count(
73
+						'sys_file_processedfile',
74
+						[
75
+							'storage' => $storage->getUid()
76
+						]
77
+					);
78
+
79
+				// Remove the record as well.
80
+				$this->getDataService()->delete('sys_file_processedfile', ['storage' => $storage->getUid()]);
81
+
82
+				$message = sprintf('Done! Removed %s records from "sys_file_processedfile".', $count);
83
+				$this->outputLine($message);
84
+			}
85
+
86
+		}
87
+
88
+		// Remove possible remaining "sys_file_processedfile"
89
+		$this
90
+			->getConnection('sys_file_processedfile')
91
+			->query('TRUNCATE sys_file_processedfile');
92
+	}
93
+
94
+	/**
95
+	 * @return \Fab\Media\Cache\CacheService|object
96
+	 */
97
+	protected function getCacheService()
98
+	{
99
+		return GeneralUtility::makeInstance(\Fab\Media\Cache\CacheService::class);
100
+	}
101
+
102
+	/**
103
+	 * @return StorageRepository|object
104
+	 */
105
+	protected function getStorageRepository()
106
+	{
107
+		return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class);
108
+	}
109
+
110
+	/**
111
+	 * @return object|DataService
112
+	 */
113
+	protected function getDataService(): DataService
114
+	{
115
+		return GeneralUtility::makeInstance(DataService::class);
116
+	}
117
+
118
+	/**
119
+	 * @param string $tableName
120
+	 * @return object|Connection
121
+	 */
122
+	protected function getConnection($tableName): Connection
123
+	{
124
+		/** @var ConnectionPool $connectionPool */
125
+		$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
126
+		return $connectionPool->getConnectionForTable($tableName);
127
+	}
128 128
 
129 129
 }
Please login to merge, or discard this patch.
Classes/Index/IndexAnalyser.php 1 patch
Indentation   +160 added lines, -160 removed lines patch added patch discarded remove patch
@@ -22,169 +22,169 @@
 block discarded – undo
22 22
 class IndexAnalyser implements SingletonInterface
23 23
 {
24 24
 
25
-    /**
26
-     * Return missing file for a given storage.
27
-     *
28
-     * @param ResourceStorage $storage
29
-     * @return array
30
-     */
31
-    public function searchForMissingFiles(ResourceStorage $storage)
32
-    {
33
-
34
-        /** @var ConnectionPool $connectionPool */
35
-        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
36
-        $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_file');
37
-
38
-        $missingFiles = [];
39
-        $statement = $queryBuilder
40
-            ->select('*')
41
-            ->from('sys_file')
42
-            ->where(
43
-                $queryBuilder->expr()->eq('storage', $storage->getUid())
44
-            )->execute();
45
-        while ($row = $statement->fetchAssociative()) {
46
-
47
-            // This task is very memory consuming on large data set e.g > 20'000 records.
48
-            // We must think of having a pagination if there is the need for such thing.
49
-            $file = ResourceFactory::getInstance()->getFileObject($row['uid'], $row);
50
-            if (!$file->exists()) {
51
-                $missingFiles[] = $file;
52
-            }
53
-        }
54
-        return $missingFiles;
55
-    }
56
-
57
-    /**
58
-     * Deletes all missing files for a given storage.
59
-     *
60
-     * @param ResourceStorage $storage
61
-     * @return array
62
-     * @throws \InvalidArgumentException
63
-     */
64
-    public function deleteMissingFiles(ResourceStorage $storage)
65
-    {
66
-        /** @var FileReferenceService $fileReferenceService */
67
-        $fileReferenceService = GeneralUtility::makeInstance(FileReferenceService::class);
68
-        $missingFiles = $this->searchForMissingFiles($storage);
69
-        $deletedFiles = [];
70
-
71
-        /** @var ConnectionPool $connectionPool */
72
-        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
73
-
74
-        /** @var \TYPO3\CMS\Core\Resource\File $missingFile */
75
-        foreach ($missingFiles as $missingFile) {
76
-            try {
77
-                // if missingFile has no file references
78
-                if ($missingFile && count($fileReferenceService->findFileReferences($missingFile)) === 0) {
79
-                    // The case is special as we have a missing file in the file system
80
-                    // As a result, we can't use $fileObject->delete(); which will
81
-                    // raise exception "Error while fetching permissions"
82
-                    $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_file');
83
-                    $queryBuilder->delete('sys_file')
84
-                        ->where($queryBuilder->expr()->eq('uid', $missingFile->getUid()))
85
-                        ->execute();
86
-
87
-                    $deletedFiles[$missingFile->getUid()] = $missingFile->getIdentifier();
88
-                }
89
-            } catch (\Exception $e) {
90
-                continue;
91
-            }
92
-        }
93
-        return $deletedFiles;
94
-    }
95
-
96
-    /*
25
+	/**
26
+	 * Return missing file for a given storage.
27
+	 *
28
+	 * @param ResourceStorage $storage
29
+	 * @return array
30
+	 */
31
+	public function searchForMissingFiles(ResourceStorage $storage)
32
+	{
33
+
34
+		/** @var ConnectionPool $connectionPool */
35
+		$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
36
+		$queryBuilder = $connectionPool->getQueryBuilderForTable('sys_file');
37
+
38
+		$missingFiles = [];
39
+		$statement = $queryBuilder
40
+			->select('*')
41
+			->from('sys_file')
42
+			->where(
43
+				$queryBuilder->expr()->eq('storage', $storage->getUid())
44
+			)->execute();
45
+		while ($row = $statement->fetchAssociative()) {
46
+
47
+			// This task is very memory consuming on large data set e.g > 20'000 records.
48
+			// We must think of having a pagination if there is the need for such thing.
49
+			$file = ResourceFactory::getInstance()->getFileObject($row['uid'], $row);
50
+			if (!$file->exists()) {
51
+				$missingFiles[] = $file;
52
+			}
53
+		}
54
+		return $missingFiles;
55
+	}
56
+
57
+	/**
58
+	 * Deletes all missing files for a given storage.
59
+	 *
60
+	 * @param ResourceStorage $storage
61
+	 * @return array
62
+	 * @throws \InvalidArgumentException
63
+	 */
64
+	public function deleteMissingFiles(ResourceStorage $storage)
65
+	{
66
+		/** @var FileReferenceService $fileReferenceService */
67
+		$fileReferenceService = GeneralUtility::makeInstance(FileReferenceService::class);
68
+		$missingFiles = $this->searchForMissingFiles($storage);
69
+		$deletedFiles = [];
70
+
71
+		/** @var ConnectionPool $connectionPool */
72
+		$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
73
+
74
+		/** @var \TYPO3\CMS\Core\Resource\File $missingFile */
75
+		foreach ($missingFiles as $missingFile) {
76
+			try {
77
+				// if missingFile has no file references
78
+				if ($missingFile && count($fileReferenceService->findFileReferences($missingFile)) === 0) {
79
+					// The case is special as we have a missing file in the file system
80
+					// As a result, we can't use $fileObject->delete(); which will
81
+					// raise exception "Error while fetching permissions"
82
+					$queryBuilder = $connectionPool->getQueryBuilderForTable('sys_file');
83
+					$queryBuilder->delete('sys_file')
84
+						->where($queryBuilder->expr()->eq('uid', $missingFile->getUid()))
85
+						->execute();
86
+
87
+					$deletedFiles[$missingFile->getUid()] = $missingFile->getIdentifier();
88
+				}
89
+			} catch (\Exception $e) {
90
+				continue;
91
+			}
92
+		}
93
+		return $deletedFiles;
94
+	}
95
+
96
+	/*
97 97
      * Return duplicates file records
98 98
      *
99 99
      * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storage
100 100
      * @return array
101 101
      */
102
-    public function searchForDuplicateIdentifiers(ResourceStorage $storage)
103
-    {
104
-        /** @var ConnectionPool $connectionPool */
105
-        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
106
-        $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_file');
107
-
108
-        $statement = $queryBuilder
109
-            ->select('*')
110
-            ->from('sys_file')
111
-            ->where(
112
-                $queryBuilder->expr()->eq('storage', $storage->getUid())
113
-            )
114
-            ->groupby('identifier')
115
-            ->having('count(*) > 1')
116
-            ->execute();
117
-
118
-        // Detect duplicate records.
119
-        $duplicates = [];
120
-        while ($row = $statement->fetchAssociative()) {
121
-
122
-            $records = $queryBuilder
123
-                ->select('*')
124
-                ->from('sys_file')
125
-                ->where(
126
-                    $queryBuilder->expr()->eq('storage', $storage->getUid())
127
-                )
128
-                ->andWhere(
129
-                    $queryBuilder->expr()->eq('identifier', $queryBuilder->createNamedParameter($row['identifier']))
130
-                )
131
-                ->execute();
132
-            $records = $records->fetchAllAssociative();
133
-            $duplicates[$row['identifier']] = $records;
134
-        }
135
-        return $duplicates;
136
-    }
137
-
138
-    /**
139
-     * Return duplicates file records
140
-     *
141
-     * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storage
142
-     * @return array
143
-     */
144
-    public function searchForDuplicateSha1(ResourceStorage $storage)
145
-    {
146
-        /** @var ConnectionPool $connectionPool */
147
-        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
148
-        $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_file');
149
-
150
-        $statement = $queryBuilder
151
-            ->select('*')
152
-            ->from('sys_file')
153
-            ->where(
154
-                $queryBuilder->expr()->eq('storage', $storage->getUid())
155
-            )
156
-            ->groupby('sha1')
157
-            ->having('count(*) > 1')
158
-            ->execute();
159
-
160
-        // Detect duplicate records.
161
-        $duplicates = [];
162
-        while ($row = $statement->fetchAssociative()) {
163
-
164
-            $records = $queryBuilder
165
-                ->select('*')
166
-                ->from('sys_file')
167
-                ->where(
168
-                    $queryBuilder->expr()->eq('storage', $storage->getUid())
169
-                )
170
-                ->andWhere(
171
-                    $queryBuilder->expr()->eq('identifier', $queryBuilder->createNamedParameter($row['sha1']))
172
-                )
173
-                ->execute();
174
-            $records = $records->fetchAllAssociative();
175
-            $duplicates[$row['sha1']] = $records;
176
-        }
177
-        return $duplicates;
178
-    }
179
-
180
-    /**
181
-     * @param string $tableName
182
-     * @return object|QueryBuilder
183
-     */
184
-    protected function getQueryBuilder($tableName): QueryBuilder
185
-    {
186
-        /** @var ConnectionPool $connectionPool */
187
-        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
188
-        return $connectionPool->getQueryBuilderForTable($tableName);
189
-    }
102
+	public function searchForDuplicateIdentifiers(ResourceStorage $storage)
103
+	{
104
+		/** @var ConnectionPool $connectionPool */
105
+		$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
106
+		$queryBuilder = $connectionPool->getQueryBuilderForTable('sys_file');
107
+
108
+		$statement = $queryBuilder
109
+			->select('*')
110
+			->from('sys_file')
111
+			->where(
112
+				$queryBuilder->expr()->eq('storage', $storage->getUid())
113
+			)
114
+			->groupby('identifier')
115
+			->having('count(*) > 1')
116
+			->execute();
117
+
118
+		// Detect duplicate records.
119
+		$duplicates = [];
120
+		while ($row = $statement->fetchAssociative()) {
121
+
122
+			$records = $queryBuilder
123
+				->select('*')
124
+				->from('sys_file')
125
+				->where(
126
+					$queryBuilder->expr()->eq('storage', $storage->getUid())
127
+				)
128
+				->andWhere(
129
+					$queryBuilder->expr()->eq('identifier', $queryBuilder->createNamedParameter($row['identifier']))
130
+				)
131
+				->execute();
132
+			$records = $records->fetchAllAssociative();
133
+			$duplicates[$row['identifier']] = $records;
134
+		}
135
+		return $duplicates;
136
+	}
137
+
138
+	/**
139
+	 * Return duplicates file records
140
+	 *
141
+	 * @param \TYPO3\CMS\Core\Resource\ResourceStorage $storage
142
+	 * @return array
143
+	 */
144
+	public function searchForDuplicateSha1(ResourceStorage $storage)
145
+	{
146
+		/** @var ConnectionPool $connectionPool */
147
+		$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
148
+		$queryBuilder = $connectionPool->getQueryBuilderForTable('sys_file');
149
+
150
+		$statement = $queryBuilder
151
+			->select('*')
152
+			->from('sys_file')
153
+			->where(
154
+				$queryBuilder->expr()->eq('storage', $storage->getUid())
155
+			)
156
+			->groupby('sha1')
157
+			->having('count(*) > 1')
158
+			->execute();
159
+
160
+		// Detect duplicate records.
161
+		$duplicates = [];
162
+		while ($row = $statement->fetchAssociative()) {
163
+
164
+			$records = $queryBuilder
165
+				->select('*')
166
+				->from('sys_file')
167
+				->where(
168
+					$queryBuilder->expr()->eq('storage', $storage->getUid())
169
+				)
170
+				->andWhere(
171
+					$queryBuilder->expr()->eq('identifier', $queryBuilder->createNamedParameter($row['sha1']))
172
+				)
173
+				->execute();
174
+			$records = $records->fetchAllAssociative();
175
+			$duplicates[$row['sha1']] = $records;
176
+		}
177
+		return $duplicates;
178
+	}
179
+
180
+	/**
181
+	 * @param string $tableName
182
+	 * @return object|QueryBuilder
183
+	 */
184
+	protected function getQueryBuilder($tableName): QueryBuilder
185
+	{
186
+		/** @var ConnectionPool $connectionPool */
187
+		$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
188
+		return $connectionPool->getQueryBuilderForTable($tableName);
189
+	}
190 190
 }
Please login to merge, or discard this patch.
ext_localconf.php 1 patch
Indentation   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -3,39 +3,39 @@
 block discarded – undo
3 3
 
4 4
 call_user_func(function () {
5 5
 
6
-    $configuration = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
7
-        \TYPO3\CMS\Core\Configuration\ExtensionConfiguration::class
8
-    )->get('media');
6
+	$configuration = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
7
+		\TYPO3\CMS\Core\Configuration\ExtensionConfiguration::class
8
+	)->get('media');
9 9
 
10
-    $GLOBALS['TYPO3_CONF_VARS']['SYS']['formEngine']['nodeRegistry'][1547054767] = [
11
-        'nodeName' => 'findUploader',
12
-        'priority' => 40,
13
-        'class' => \Fab\Media\Backend\TceForms::class,
14
-    ];
10
+	$GLOBALS['TYPO3_CONF_VARS']['SYS']['formEngine']['nodeRegistry'][1547054767] = [
11
+		'nodeName' => 'findUploader',
12
+		'priority' => 40,
13
+		'class' => \Fab\Media\Backend\TceForms::class,
14
+	];
15 15
 
16
-    $disableTitleMetadataExtractor = isset($configuration['disable_title_metadata_extractor']) ? $configuration['disable_title_metadata_extractor'] : FALSE;
17
-    if (!$disableTitleMetadataExtractor) {
16
+	$disableTitleMetadataExtractor = isset($configuration['disable_title_metadata_extractor']) ? $configuration['disable_title_metadata_extractor'] : FALSE;
17
+	if (!$disableTitleMetadataExtractor) {
18 18
 
19
-        // Register basic metadata extractor. Will feed the file with a "title" when indexing, e.g. upload, through scheduler
20
-        \TYPO3\CMS\Core\Resource\Index\ExtractorRegistry::getInstance()->registerExtractionService(\Fab\Media\Index\TitleMetadataExtractor::class );
21
-    }
19
+		// Register basic metadata extractor. Will feed the file with a "title" when indexing, e.g. upload, through scheduler
20
+		\TYPO3\CMS\Core\Resource\Index\ExtractorRegistry::getInstance()->registerExtractionService(\Fab\Media\Index\TitleMetadataExtractor::class );
21
+	}
22 22
 
23
-    // Hook for traditional file upload, trigger metadata indexing as well.
24
-    // Could be done at the Core level in the future...
25
-    $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_extfilefunc.php']['processData'][] = 'Fab\Media\Hook\FileUploadHook';
23
+	// Hook for traditional file upload, trigger metadata indexing as well.
24
+	// Could be done at the Core level in the future...
25
+	$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_extfilefunc.php']['processData'][] = 'Fab\Media\Hook\FileUploadHook';
26 26
 
27
-    if (TYPO3_MODE === 'BE') {
27
+	if (TYPO3_MODE === 'BE') {
28 28
 
29
-        // Special process to fill column "usage" which indicates the total number of file reference including soft references.
30
-        $GLOBALS ['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][] = 'Fab\Media\Hook\DataHandlerHook';
29
+		// Special process to fill column "usage" which indicates the total number of file reference including soft references.
30
+		$GLOBALS ['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][] = 'Fab\Media\Hook\DataHandlerHook';
31 31
 
32
-        $hasMediaFilePicker = isset($configuration['has_media_file_picker']) ? $configuration['has_media_file_picker'] : FALSE;
33
-        if ($hasMediaFilePicker) {
32
+		$hasMediaFilePicker = isset($configuration['has_media_file_picker']) ? $configuration['has_media_file_picker'] : FALSE;
33
+		if ($hasMediaFilePicker) {
34 34
 
35
-            // Override classes for the Object Manager.
36
-            $GLOBALS['TYPO3_CONF_VARS']['SYS']['Objects'][\TYPO3\CMS\Backend\Form\FormResultCompiler::class] = array(
37
-                'className' => \Fab\Media\Override\Backend\Form\FormResultCompiler::class
38
-            );
39
-        }
40
-    }
35
+			// Override classes for the Object Manager.
36
+			$GLOBALS['TYPO3_CONF_VARS']['SYS']['Objects'][\TYPO3\CMS\Backend\Form\FormResultCompiler::class] = array(
37
+				'className' => \Fab\Media\Override\Backend\Form\FormResultCompiler::class
38
+			);
39
+		}
40
+	}
41 41
 });
42 42
\ No newline at end of file
Please login to merge, or discard this patch.
ext_emconf.php 1 patch
Indentation   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -1,30 +1,30 @@
 block discarded – undo
1 1
 <?php
2 2
 
3 3
 $EM_CONF[$_EXTKEY] = [
4
-    'title' => 'Media management',
5
-    'description' => 'Media management system for TYPO3 CMS.',
6
-    'category' => 'module',
7
-    'author' => 'Fabien Udriot',
8
-    'author_email' => '[email protected]',
9
-    'state' => 'stable',
10
-    'version' => '5.2.0-dev',
11
-    'autoload' => [
12
-        'psr-4' => ['Fab\\Media\\' => 'Classes']
13
-    ],
14
-    'constraints' =>
15
-        [
16
-            'depends' =>
17
-                [
18
-                    'typo3' => '10.4.0-10.4.99',
19
-                    'vidi' => '4.0.0-0.0.0',
20
-                ],
21
-            'conflicts' =>
22
-                [
23
-                ],
24
-            'suggests' =>
25
-                [
26
-                    'metadata' => '',
27
-                    'filemetadata' => '',
28
-                ],
29
-        ]
4
+	'title' => 'Media management',
5
+	'description' => 'Media management system for TYPO3 CMS.',
6
+	'category' => 'module',
7
+	'author' => 'Fabien Udriot',
8
+	'author_email' => '[email protected]',
9
+	'state' => 'stable',
10
+	'version' => '5.2.0-dev',
11
+	'autoload' => [
12
+		'psr-4' => ['Fab\\Media\\' => 'Classes']
13
+	],
14
+	'constraints' =>
15
+		[
16
+			'depends' =>
17
+				[
18
+					'typo3' => '10.4.0-10.4.99',
19
+					'vidi' => '4.0.0-0.0.0',
20
+				],
21
+			'conflicts' =>
22
+				[
23
+				],
24
+			'suggests' =>
25
+				[
26
+					'metadata' => '',
27
+					'filemetadata' => '',
28
+				],
29
+		]
30 30
 ];
Please login to merge, or discard this patch.
Classes/Backend/TceForms.php 1 patch
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -20,37 +20,37 @@
 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('core') . 'Resources/Public/JavaScript/Contrib/jquery/jquery.min.js');
38
-        $pageRenderer->addJsFile(ExtensionManagementUtility::extPath('media') . 'Resources/Public/JavaScript/Encoder.js');
39
-        $pageRenderer->addJsFile(ExtensionManagementUtility::extPath('media') . 'Resources/Public/Libraries/Fineuploader/jquery.fineuploader-5.0.9.min.js');
40
-
41
-        $result = $this->initializeResultArray();
42
-
43
-        $fileMetadataRecord = $this->data['databaseRow'];
44
-
45
-        if ($fileMetadataRecord['file'] <= 0) {
46
-            throw new \Exception('I could not find a valid file identifier', 1392926871);
47
-        }
48
-
49
-        /** @var $fileUpload \Fab\Media\Form\FileUploadTceForms */
50
-        $fileUpload = GeneralUtility::makeInstance(\Fab\Media\Form\FileUploadTceForms::class);
51
-        $fileUpload->setValue($fileMetadataRecord['file'][0])->setPrefix(MediaModule::getParameterPrefix());
52
-        $result['html'] = $fileUpload->render();
53
-        return $result;
54
-    }
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('core') . 'Resources/Public/JavaScript/Contrib/jquery/jquery.min.js');
38
+		$pageRenderer->addJsFile(ExtensionManagementUtility::extPath('media') . 'Resources/Public/JavaScript/Encoder.js');
39
+		$pageRenderer->addJsFile(ExtensionManagementUtility::extPath('media') . 'Resources/Public/Libraries/Fineuploader/jquery.fineuploader-5.0.9.min.js');
40
+
41
+		$result = $this->initializeResultArray();
42
+
43
+		$fileMetadataRecord = $this->data['databaseRow'];
44
+
45
+		if ($fileMetadataRecord['file'] <= 0) {
46
+			throw new \Exception('I could not find a valid file identifier', 1392926871);
47
+		}
48
+
49
+		/** @var $fileUpload \Fab\Media\Form\FileUploadTceForms */
50
+		$fileUpload = GeneralUtility::makeInstance(\Fab\Media\Form\FileUploadTceForms::class);
51
+		$fileUpload->setValue($fileMetadataRecord['file'][0])->setPrefix(MediaModule::getParameterPrefix());
52
+		$result['html'] = $fileUpload->render();
53
+		return $result;
54
+	}
55 55
 
56 56
 }
Please login to merge, or discard this patch.
Classes/Controller/AssetController.php 1 patch
Indentation   +309 added lines, -309 removed lines patch added patch discarded remove patch
@@ -42,314 +42,314 @@
 block discarded – undo
42 42
 class AssetController extends ActionController
43 43
 {
44 44
 
45
-    /**
46
-     * @var string
47
-     */
48
-    protected $dataType = 'sys_file';
49
-
50
-    /**
51
-     * @throws \Fab\Media\Exception\StorageNotOnlineException
52
-     * @throws \InvalidArgumentException
53
-     * @throws \TYPO3\CMS\Extbase\Mvc\Exception\NoSuchArgumentException
54
-     */
55
-    public function initializeAction()
56
-    {
57
-        $pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
58
-        $pageRenderer->addInlineLanguageLabelFile('EXT:media/Resources/Private/Language/locallang.xlf');
59
-
60
-        // Configure property mapping to retrieve the file object.
61
-        if ($this->arguments->hasArgument('file')) {
62
-
63
-            /** @var FileConverter $typeConverter */
64
-            $typeConverter = $this->objectManager->get(FileConverter::class);
65
-
66
-            $propertyMappingConfiguration = $this->arguments->getArgument('file')->getPropertyMappingConfiguration();
67
-            $propertyMappingConfiguration->setTypeConverter($typeConverter);
68
-        }
69
-    }
70
-
71
-    /**
72
-     * Force download of the file.
73
-     *
74
-     * @param File $file
75
-     * @param bool $forceDownload
76
-     * @return bool|string
77
-     * @throws \RuntimeException
78
-     */
79
-    public function downloadAction(File $file, $forceDownload = false)
80
-    {
81
-
82
-        if ($file->exists() && $file->getStorage()->isWithinFileMountBoundaries($file->getParentFolder())) {
83
-
84
-            // Emit signal before downloading the file.
85
-            $this->emitBeforeDownloadSignal($file);
86
-
87
-            // Read the file and dump it with the flag "forceDownload" set to true or false.
88
-            $file->getStorage()->dumpFileContents($file, $forceDownload);
89
-
90
-            $result = true;
91
-        } else {
92
-            $result = 'Access denied!';
93
-        }
94
-
95
-        return $result;
96
-    }
97
-
98
-    /**
99
-     * Handle file upload for a new file.
100
-     *
101
-     * @param string $combinedIdentifier
102
-     * @Extbase\Validate("\Fab\Media\Domain\Validator\StorageValidator", param="combinedIdentifier")
103
-     * @return string
104
-     */
105
-    public function createAction($combinedIdentifier)
106
-    {
107
-        /** @var UploadedFileInterface $uploadedFile */
108
-        $uploadedFile = $this->handleUpload();
109
-        if (!is_object($uploadedFile)) {
110
-            return htmlspecialchars(json_encode($uploadedFile), ENT_NOQUOTES);
111
-        }
112
-
113
-        // Get the target folder.
114
-        if ($this->getMediaModule()->hasFolderTree()) {
115
-            $targetFolder = $this->getMediaModule()->getFolderForCombinedIdentifier($combinedIdentifier);
116
-        } else {
117
-            $storage = ResourceFactory::getInstance()->getStorageObjectFromCombinedIdentifier($combinedIdentifier);
118
-            $targetFolder = $this->getMediaModule()->getTargetFolderForUploadedFile($uploadedFile, $storage);
119
-        }
120
-
121
-        try {
122
-            $conflictMode = DuplicationBehavior::RENAME;
123
-            $fileName = $uploadedFile->getName();
124
-            $file = $targetFolder->addFile($uploadedFile->getFileWithAbsolutePath(), $fileName, $conflictMode);
125
-
126
-            // Run the indexer for extracting metadata.
127
-            $this->getMediaIndexer($file->getStorage())
128
-                ->extractMetadata($file)
129
-                ->applyDefaultCategories($file);
130
-
131
-            $response = array(
132
-                'success' => true,
133
-                'uid' => $file->getUid(),
134
-                'name' => $file->getName(),
135
-                'thumbnail' => $this->getThumbnailService($file)->create(),
136
-            );
137
-        } catch (UploadException $e) {
138
-            $response = array('error' => 'The upload has failed, no uploaded file found!');
139
-        } catch (InsufficientUserPermissionsException $e) {
140
-            $response = array('error' => 'You are not allowed to upload files!');
141
-        } catch (UploadSizeException $e) {
142
-            $response = array('error' => vsprintf('The uploaded file "%s" exceeds the size-limit', array($uploadedFile->getName())));
143
-        } catch (InsufficientFolderWritePermissionsException $e) {
144
-            $response = array('error' => vsprintf('Destination path "%s" was not within your mount points!', array($targetFolder->getIdentifier())));
145
-        } catch (IllegalFileExtensionException $e) {
146
-            $response = array('error' => vsprintf('Extension of file name "%s" is not allowed in "%s"!', array($uploadedFile->getName(), $targetFolder->getIdentifier())));
147
-        } catch (ExistingTargetFileNameException $e) {
148
-            $response = array('error' => vsprintf('No unique filename available in "%s"!', array($targetFolder->getIdentifier())));
149
-        } catch (\RuntimeException $e) {
150
-            $response = array('error' => vsprintf('Uploaded file could not be moved! Write-permission problem in "%s"?', array($targetFolder->getIdentifier())));
151
-        }
152
-
153
-        // to pass data through iframe you will need to encode all html tags
154
-        header("Content-Type: text/plain");
155
-        return htmlspecialchars(json_encode($response), ENT_NOQUOTES);
156
-    }
157
-
158
-    /**
159
-     * Handle file upload for an existing file.
160
-     *
161
-     * @param File $file
162
-     * @return string
163
-     * @throws \InvalidArgumentException
164
-     * @throws \RuntimeException
165
-     */
166
-    public function updateAction(File $file)
167
-    {
168
-        $uploadedFile = $this->handleUpload();
169
-        if (!is_object($uploadedFile)) {
170
-            return htmlspecialchars(json_encode($uploadedFile), ENT_NOQUOTES);
171
-        }
172
-
173
-        /** @var $file File */
174
-        $targetFolder = $file->getStorage()->getFolder(dirname($file->getIdentifier()));
175
-
176
-        try {
177
-            $storage = $file->getStorage();
178
-            $storage->replaceFile($file, $uploadedFile->getFileWithAbsolutePath());
179
-
180
-            // Run the indexer for extracting metadata.
181
-            $this->getMediaIndexer($file->getStorage())
182
-                ->updateIndex($file)
183
-                ->extractMetadata($file);
184
-
185
-            // Clear cache on pages holding a reference to this file.
186
-            $this->getCacheService()->clearCache($file);
187
-
188
-            $response = array(
189
-                'success' => true,
190
-                'uid' => $file->getUid(),
191
-                'name' => $file->getName(),
192
-                'thumbnail' => $this->getThumbnailService($file)->create(),
193
-                'fileInfo' => $this->getMetadataViewHelper()->render($file),
194
-            );
195
-        } catch (UploadException $e) {
196
-            $response = array('error' => 'The upload has failed, no uploaded file found!');
197
-        } catch (InsufficientUserPermissionsException $e) {
198
-            $response = array('error' => 'You are not allowed to upload files!');
199
-        } catch (UploadSizeException $e) {
200
-            $response = array('error' => vsprintf('The uploaded file "%s" exceeds the size-limit', array($uploadedFile->getName())));
201
-        } catch (InsufficientFolderWritePermissionsException $e) {
202
-            $response = array('error' => vsprintf('Destination path "%s" was not within your mount points!', array($targetFolder->getIdentifier())));
203
-        } catch (IllegalFileExtensionException $e) {
204
-            $response = array('error' => vsprintf('Extension of file name "%s" is not allowed in "%s"!', array($uploadedFile->getName(), $targetFolder->getIdentifier())));
205
-        } catch (ExistingTargetFileNameException $e) {
206
-            $response = array('error' => vsprintf('No unique filename available in "%s"!', array($targetFolder->getIdentifier())));
207
-        } catch (\RuntimeException $e) {
208
-            $response = array('error' => vsprintf('Uploaded file could not be moved! Write-permission problem in "%s"?', array($targetFolder->getIdentifier())));
209
-        }
210
-
211
-        // to pass data through iframe you will need to encode all html tags
212
-        header("Content-Type: text/plain");
213
-        return htmlspecialchars(json_encode($response), ENT_NOQUOTES);
214
-    }
215
-
216
-    /**
217
-     * Returns an editing form for moving Files between storage.
218
-     *
219
-     * @param array $matches
220
-     * @throws \Exception
221
-     */
222
-    public function editStorageAction(array $matches = [])
223
-    {
224
-
225
-        $this->view->assign('storages', $this->getMediaModule()->getAllowedStorages());
226
-        $this->view->assign('storageTitle', Tca::table('sys_file_storage')->getTitle());
227
-
228
-        $fieldName = 'storage';
229
-
230
-        // Instantiate the Matcher object according different rules.
231
-        $matcher = MatcherObjectFactory::getInstance()->getMatcher($matches, $this->dataType);
232
-
233
-        // Fetch objects via the Content Service.
234
-        $contentService = $this->getContentService()->findBy($matcher);
235
-
236
-        $fieldType = Tca::table($this->dataType)->field($fieldName)->getType();
237
-
238
-        $this->view->assign('fieldType', ucfirst($fieldType));
239
-        $this->view->assign('dataType', $this->dataType);
240
-        $this->view->assign('matches', $matches);
241
-        $this->view->assign('fieldNameAndPath', $fieldName);
242
-        $this->view->assign('numberOfObjects', $contentService->getNumberOfObjects());
243
-        $this->view->assign('editWholeSelection', empty($matches['uid'])); // necessary??
244
-    }
245
-
246
-    /**
247
-     * Handle file upload.
248
-     *
249
-     * @return \Fab\Media\FileUpload\UploadedFileInterface|array
250
-     * @throws \InvalidArgumentException
251
-     */
252
-    protected function handleUpload()
253
-    {
254
-
255
-        /** @var $uploadManager UploadManager */
256
-        $uploadManager = GeneralUtility::makeInstance(UploadManager::class);
257
-
258
-        try {
259
-            /** @var $result \Fab\Media\FileUpload\UploadedFileInterface */
260
-            $result = $uploadManager->handleUpload();
261
-        } catch (\Exception $e) {
262
-            $result = array('error' => $e->getMessage());
263
-        }
264
-
265
-        return $result;
266
-    }
267
-
268
-    /**
269
-     * @return MetadataViewHelper
270
-     * @throws \InvalidArgumentException
271
-     */
272
-    protected function getMetadataViewHelper()
273
-    {
274
-        return GeneralUtility::makeInstance(MetadataViewHelper::class);
275
-    }
276
-
277
-    /**
278
-     * @param File $file
279
-     * @return ThumbnailService
280
-     * @throws \Fab\Media\Exception\InvalidKeyInArrayException
281
-     * @throws \InvalidArgumentException
282
-     */
283
-    protected function getThumbnailService(File $file)
284
-    {
285
-
286
-        /** @var $thumbnailService ThumbnailService */
287
-        $thumbnailService = GeneralUtility::makeInstance(ThumbnailService::class, $file);
288
-        $thumbnailService->setAppendTimeStamp(true)
289
-            ->setOutputType(ThumbnailInterface::OUTPUT_IMAGE_WRAPPED);
290
-        return $thumbnailService;
291
-    }
292
-
293
-    /**
294
-     * Get the instance of the Indexer service to update the metadata of the file.
295
-     *
296
-     * @param int|ResourceStorage $storage
297
-     * @return MediaIndexer
298
-     * @throws \InvalidArgumentException
299
-     */
300
-    protected function getMediaIndexer($storage)
301
-    {
302
-        return GeneralUtility::makeInstance(MediaIndexer::class, $storage);
303
-    }
304
-
305
-    /**
306
-     * @return CacheService
307
-     * @throws \InvalidArgumentException
308
-     */
309
-    protected function getCacheService()
310
-    {
311
-        return GeneralUtility::makeInstance(CacheService::class);
312
-    }
313
-
314
-    /**
315
-     * Signal that is emitted before a file is downloaded.
316
-     *
317
-     * @param File $file
318
-     * @return void
319
-     * @throws \TYPO3\CMS\Extbase\SignalSlot\Exception\InvalidSlotReturnException
320
-     * @throws \TYPO3\CMS\Extbase\SignalSlot\Exception\InvalidSlotException
321
-     */
322
-    protected function emitBeforeDownloadSignal(File $file)
323
-    {
324
-        $this->getSignalSlotDispatcher()->dispatch('Fab\Media\Controller\Backend\AssetController', 'beforeDownload', array($file));
325
-    }
326
-
327
-    /**
328
-     * Get the SignalSlot dispatcher.
329
-     *
330
-     * @return Dispatcher
331
-     */
332
-    protected function getSignalSlotDispatcher()
333
-    {
334
-        return $this->objectManager->get(Dispatcher::class);
335
-    }
336
-
337
-    /**
338
-     * @return ContentService
339
-     * @throws \InvalidArgumentException
340
-     */
341
-    protected function getContentService()
342
-    {
343
-        return GeneralUtility::makeInstance(ContentService::class, $this->dataType);
344
-    }
345
-
346
-    /**
347
-     * @return MediaModule|object
348
-     * @throws \InvalidArgumentException
349
-     */
350
-    protected function getMediaModule()
351
-    {
352
-        return GeneralUtility::makeInstance(MediaModule::class);
353
-    }
45
+	/**
46
+	 * @var string
47
+	 */
48
+	protected $dataType = 'sys_file';
49
+
50
+	/**
51
+	 * @throws \Fab\Media\Exception\StorageNotOnlineException
52
+	 * @throws \InvalidArgumentException
53
+	 * @throws \TYPO3\CMS\Extbase\Mvc\Exception\NoSuchArgumentException
54
+	 */
55
+	public function initializeAction()
56
+	{
57
+		$pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
58
+		$pageRenderer->addInlineLanguageLabelFile('EXT:media/Resources/Private/Language/locallang.xlf');
59
+
60
+		// Configure property mapping to retrieve the file object.
61
+		if ($this->arguments->hasArgument('file')) {
62
+
63
+			/** @var FileConverter $typeConverter */
64
+			$typeConverter = $this->objectManager->get(FileConverter::class);
65
+
66
+			$propertyMappingConfiguration = $this->arguments->getArgument('file')->getPropertyMappingConfiguration();
67
+			$propertyMappingConfiguration->setTypeConverter($typeConverter);
68
+		}
69
+	}
70
+
71
+	/**
72
+	 * Force download of the file.
73
+	 *
74
+	 * @param File $file
75
+	 * @param bool $forceDownload
76
+	 * @return bool|string
77
+	 * @throws \RuntimeException
78
+	 */
79
+	public function downloadAction(File $file, $forceDownload = false)
80
+	{
81
+
82
+		if ($file->exists() && $file->getStorage()->isWithinFileMountBoundaries($file->getParentFolder())) {
83
+
84
+			// Emit signal before downloading the file.
85
+			$this->emitBeforeDownloadSignal($file);
86
+
87
+			// Read the file and dump it with the flag "forceDownload" set to true or false.
88
+			$file->getStorage()->dumpFileContents($file, $forceDownload);
89
+
90
+			$result = true;
91
+		} else {
92
+			$result = 'Access denied!';
93
+		}
94
+
95
+		return $result;
96
+	}
97
+
98
+	/**
99
+	 * Handle file upload for a new file.
100
+	 *
101
+	 * @param string $combinedIdentifier
102
+	 * @Extbase\Validate("\Fab\Media\Domain\Validator\StorageValidator", param="combinedIdentifier")
103
+	 * @return string
104
+	 */
105
+	public function createAction($combinedIdentifier)
106
+	{
107
+		/** @var UploadedFileInterface $uploadedFile */
108
+		$uploadedFile = $this->handleUpload();
109
+		if (!is_object($uploadedFile)) {
110
+			return htmlspecialchars(json_encode($uploadedFile), ENT_NOQUOTES);
111
+		}
112
+
113
+		// Get the target folder.
114
+		if ($this->getMediaModule()->hasFolderTree()) {
115
+			$targetFolder = $this->getMediaModule()->getFolderForCombinedIdentifier($combinedIdentifier);
116
+		} else {
117
+			$storage = ResourceFactory::getInstance()->getStorageObjectFromCombinedIdentifier($combinedIdentifier);
118
+			$targetFolder = $this->getMediaModule()->getTargetFolderForUploadedFile($uploadedFile, $storage);
119
+		}
120
+
121
+		try {
122
+			$conflictMode = DuplicationBehavior::RENAME;
123
+			$fileName = $uploadedFile->getName();
124
+			$file = $targetFolder->addFile($uploadedFile->getFileWithAbsolutePath(), $fileName, $conflictMode);
125
+
126
+			// Run the indexer for extracting metadata.
127
+			$this->getMediaIndexer($file->getStorage())
128
+				->extractMetadata($file)
129
+				->applyDefaultCategories($file);
130
+
131
+			$response = array(
132
+				'success' => true,
133
+				'uid' => $file->getUid(),
134
+				'name' => $file->getName(),
135
+				'thumbnail' => $this->getThumbnailService($file)->create(),
136
+			);
137
+		} catch (UploadException $e) {
138
+			$response = array('error' => 'The upload has failed, no uploaded file found!');
139
+		} catch (InsufficientUserPermissionsException $e) {
140
+			$response = array('error' => 'You are not allowed to upload files!');
141
+		} catch (UploadSizeException $e) {
142
+			$response = array('error' => vsprintf('The uploaded file "%s" exceeds the size-limit', array($uploadedFile->getName())));
143
+		} catch (InsufficientFolderWritePermissionsException $e) {
144
+			$response = array('error' => vsprintf('Destination path "%s" was not within your mount points!', array($targetFolder->getIdentifier())));
145
+		} catch (IllegalFileExtensionException $e) {
146
+			$response = array('error' => vsprintf('Extension of file name "%s" is not allowed in "%s"!', array($uploadedFile->getName(), $targetFolder->getIdentifier())));
147
+		} catch (ExistingTargetFileNameException $e) {
148
+			$response = array('error' => vsprintf('No unique filename available in "%s"!', array($targetFolder->getIdentifier())));
149
+		} catch (\RuntimeException $e) {
150
+			$response = array('error' => vsprintf('Uploaded file could not be moved! Write-permission problem in "%s"?', array($targetFolder->getIdentifier())));
151
+		}
152
+
153
+		// to pass data through iframe you will need to encode all html tags
154
+		header("Content-Type: text/plain");
155
+		return htmlspecialchars(json_encode($response), ENT_NOQUOTES);
156
+	}
157
+
158
+	/**
159
+	 * Handle file upload for an existing file.
160
+	 *
161
+	 * @param File $file
162
+	 * @return string
163
+	 * @throws \InvalidArgumentException
164
+	 * @throws \RuntimeException
165
+	 */
166
+	public function updateAction(File $file)
167
+	{
168
+		$uploadedFile = $this->handleUpload();
169
+		if (!is_object($uploadedFile)) {
170
+			return htmlspecialchars(json_encode($uploadedFile), ENT_NOQUOTES);
171
+		}
172
+
173
+		/** @var $file File */
174
+		$targetFolder = $file->getStorage()->getFolder(dirname($file->getIdentifier()));
175
+
176
+		try {
177
+			$storage = $file->getStorage();
178
+			$storage->replaceFile($file, $uploadedFile->getFileWithAbsolutePath());
179
+
180
+			// Run the indexer for extracting metadata.
181
+			$this->getMediaIndexer($file->getStorage())
182
+				->updateIndex($file)
183
+				->extractMetadata($file);
184
+
185
+			// Clear cache on pages holding a reference to this file.
186
+			$this->getCacheService()->clearCache($file);
187
+
188
+			$response = array(
189
+				'success' => true,
190
+				'uid' => $file->getUid(),
191
+				'name' => $file->getName(),
192
+				'thumbnail' => $this->getThumbnailService($file)->create(),
193
+				'fileInfo' => $this->getMetadataViewHelper()->render($file),
194
+			);
195
+		} catch (UploadException $e) {
196
+			$response = array('error' => 'The upload has failed, no uploaded file found!');
197
+		} catch (InsufficientUserPermissionsException $e) {
198
+			$response = array('error' => 'You are not allowed to upload files!');
199
+		} catch (UploadSizeException $e) {
200
+			$response = array('error' => vsprintf('The uploaded file "%s" exceeds the size-limit', array($uploadedFile->getName())));
201
+		} catch (InsufficientFolderWritePermissionsException $e) {
202
+			$response = array('error' => vsprintf('Destination path "%s" was not within your mount points!', array($targetFolder->getIdentifier())));
203
+		} catch (IllegalFileExtensionException $e) {
204
+			$response = array('error' => vsprintf('Extension of file name "%s" is not allowed in "%s"!', array($uploadedFile->getName(), $targetFolder->getIdentifier())));
205
+		} catch (ExistingTargetFileNameException $e) {
206
+			$response = array('error' => vsprintf('No unique filename available in "%s"!', array($targetFolder->getIdentifier())));
207
+		} catch (\RuntimeException $e) {
208
+			$response = array('error' => vsprintf('Uploaded file could not be moved! Write-permission problem in "%s"?', array($targetFolder->getIdentifier())));
209
+		}
210
+
211
+		// to pass data through iframe you will need to encode all html tags
212
+		header("Content-Type: text/plain");
213
+		return htmlspecialchars(json_encode($response), ENT_NOQUOTES);
214
+	}
215
+
216
+	/**
217
+	 * Returns an editing form for moving Files between storage.
218
+	 *
219
+	 * @param array $matches
220
+	 * @throws \Exception
221
+	 */
222
+	public function editStorageAction(array $matches = [])
223
+	{
224
+
225
+		$this->view->assign('storages', $this->getMediaModule()->getAllowedStorages());
226
+		$this->view->assign('storageTitle', Tca::table('sys_file_storage')->getTitle());
227
+
228
+		$fieldName = 'storage';
229
+
230
+		// Instantiate the Matcher object according different rules.
231
+		$matcher = MatcherObjectFactory::getInstance()->getMatcher($matches, $this->dataType);
232
+
233
+		// Fetch objects via the Content Service.
234
+		$contentService = $this->getContentService()->findBy($matcher);
235
+
236
+		$fieldType = Tca::table($this->dataType)->field($fieldName)->getType();
237
+
238
+		$this->view->assign('fieldType', ucfirst($fieldType));
239
+		$this->view->assign('dataType', $this->dataType);
240
+		$this->view->assign('matches', $matches);
241
+		$this->view->assign('fieldNameAndPath', $fieldName);
242
+		$this->view->assign('numberOfObjects', $contentService->getNumberOfObjects());
243
+		$this->view->assign('editWholeSelection', empty($matches['uid'])); // necessary??
244
+	}
245
+
246
+	/**
247
+	 * Handle file upload.
248
+	 *
249
+	 * @return \Fab\Media\FileUpload\UploadedFileInterface|array
250
+	 * @throws \InvalidArgumentException
251
+	 */
252
+	protected function handleUpload()
253
+	{
254
+
255
+		/** @var $uploadManager UploadManager */
256
+		$uploadManager = GeneralUtility::makeInstance(UploadManager::class);
257
+
258
+		try {
259
+			/** @var $result \Fab\Media\FileUpload\UploadedFileInterface */
260
+			$result = $uploadManager->handleUpload();
261
+		} catch (\Exception $e) {
262
+			$result = array('error' => $e->getMessage());
263
+		}
264
+
265
+		return $result;
266
+	}
267
+
268
+	/**
269
+	 * @return MetadataViewHelper
270
+	 * @throws \InvalidArgumentException
271
+	 */
272
+	protected function getMetadataViewHelper()
273
+	{
274
+		return GeneralUtility::makeInstance(MetadataViewHelper::class);
275
+	}
276
+
277
+	/**
278
+	 * @param File $file
279
+	 * @return ThumbnailService
280
+	 * @throws \Fab\Media\Exception\InvalidKeyInArrayException
281
+	 * @throws \InvalidArgumentException
282
+	 */
283
+	protected function getThumbnailService(File $file)
284
+	{
285
+
286
+		/** @var $thumbnailService ThumbnailService */
287
+		$thumbnailService = GeneralUtility::makeInstance(ThumbnailService::class, $file);
288
+		$thumbnailService->setAppendTimeStamp(true)
289
+			->setOutputType(ThumbnailInterface::OUTPUT_IMAGE_WRAPPED);
290
+		return $thumbnailService;
291
+	}
292
+
293
+	/**
294
+	 * Get the instance of the Indexer service to update the metadata of the file.
295
+	 *
296
+	 * @param int|ResourceStorage $storage
297
+	 * @return MediaIndexer
298
+	 * @throws \InvalidArgumentException
299
+	 */
300
+	protected function getMediaIndexer($storage)
301
+	{
302
+		return GeneralUtility::makeInstance(MediaIndexer::class, $storage);
303
+	}
304
+
305
+	/**
306
+	 * @return CacheService
307
+	 * @throws \InvalidArgumentException
308
+	 */
309
+	protected function getCacheService()
310
+	{
311
+		return GeneralUtility::makeInstance(CacheService::class);
312
+	}
313
+
314
+	/**
315
+	 * Signal that is emitted before a file is downloaded.
316
+	 *
317
+	 * @param File $file
318
+	 * @return void
319
+	 * @throws \TYPO3\CMS\Extbase\SignalSlot\Exception\InvalidSlotReturnException
320
+	 * @throws \TYPO3\CMS\Extbase\SignalSlot\Exception\InvalidSlotException
321
+	 */
322
+	protected function emitBeforeDownloadSignal(File $file)
323
+	{
324
+		$this->getSignalSlotDispatcher()->dispatch('Fab\Media\Controller\Backend\AssetController', 'beforeDownload', array($file));
325
+	}
326
+
327
+	/**
328
+	 * Get the SignalSlot dispatcher.
329
+	 *
330
+	 * @return Dispatcher
331
+	 */
332
+	protected function getSignalSlotDispatcher()
333
+	{
334
+		return $this->objectManager->get(Dispatcher::class);
335
+	}
336
+
337
+	/**
338
+	 * @return ContentService
339
+	 * @throws \InvalidArgumentException
340
+	 */
341
+	protected function getContentService()
342
+	{
343
+		return GeneralUtility::makeInstance(ContentService::class, $this->dataType);
344
+	}
345
+
346
+	/**
347
+	 * @return MediaModule|object
348
+	 * @throws \InvalidArgumentException
349
+	 */
350
+	protected function getMediaModule()
351
+	{
352
+		return GeneralUtility::makeInstance(MediaModule::class);
353
+	}
354 354
 
355 355
 }
Please login to merge, or discard this patch.