[BUGFIX] Property description placed at wrong position in BasicFileUtility
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Utility / File / BasicFileUtility.php
1 <?php
2 namespace TYPO3\CMS\Core\Utility\File;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Utility\GeneralUtility;
18 use TYPO3\CMS\Core\Utility\PathUtility;
19
20 /**
21 * Contains class with basic file management functions
22 *
23 * Contains functions for management, validation etc of files in TYPO3,
24 * using the concepts of web- and ftp-space. Please see the comment for the
25 * init() function
26 *
27 * Note: All methods in this class should not be used anymore since TYPO3 6.0.
28 * Please use corresponding TYPO3\\CMS\\Core\\Resource\\ResourceStorage
29 * (fetched via BE_USERS->getFileStorages()), as all functions should be
30 * found there (in a cleaner manner).
31 *
32 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
33 */
34 class BasicFileUtility {
35
36 /**
37 * @var string
38 */
39 const UNSAFE_FILENAME_CHARACTER_EXPRESSION = '\\x00-\\x2C\\/\\x3A-\\x3F\\x5B-\\x60\\x7B-\\xBF';
40
41 /**
42 * Prefix which will be prepended the file when using the getUniqueName-function
43 *
44 * @var string
45 */
46 public $getUniqueNamePrefix = '';
47
48 /**
49 * This number decides the highest allowed appended number used on a filename before we use naming with unique strings
50 *
51 * @var int
52 */
53 public $maxNumber = 99;
54
55 /**
56 * This number decides how many characters out of a unique MD5-hash that is appended to a filename if getUniqueName is asked to find an available filename.
57 *
58 * @var int
59 */
60 public $uniquePrecision = 6;
61
62 /**
63 * This is the maximum length of names treated by cleanFileName()
64 *
65 * @var int
66 */
67 public $maxInputNameLen = 60;
68
69 /**
70 * Temp-foldername. A folder in the root of one of the mounts with this name is regarded a TEMP-folder (used for upload from clipboard)
71 *
72 * @var string
73 */
74 public $tempFN = '_temp_';
75
76 /**
77 * @var array
78 */
79 public $f_ext = array();
80
81 /**
82 * See comment in header
83 *
84 * @var array
85 */
86 public $mounts = array();
87
88 /**
89 * See comment in header
90 *
91 * @var string
92 */
93 public $webPath = '';
94
95 /**
96 * Set to DOCUMENT_ROOT.
97 *
98 * @var bool
99 */
100 public $isInit = 0;
101
102 /**
103 * @var \TYPO3\CMS\Core\Charset\CharsetConverter
104 */
105 public $csConvObj;
106
107 /**********************************
108 *
109 * Checking functions
110 *
111 **********************************/
112 /**
113 * Constructor
114 * This function should be called to initialise the internal arrays $this->mounts and $this->f_ext
115 *
116 * A typical example of the array $mounts is this:
117 * $mounts[xx][path] = (..a mounted path..)
118 * the 'xx'-keys is just numerical from zero. There are also a [name] and [type] value that just denotes the mountname and type. Not used for athentication here.
119 * $this->mounts is traversed in the function checkPathAgainstMounts($thePath), and it is checked that $thePath is actually below one of the mount-paths
120 * The mountpaths are with a trailing '/'. $thePath must be with a trailing '/' also!
121 * As you can see, $this->mounts is very critical! This is the array that decides where the user will be allowed to copy files!!
122 *
123 * A typical example of the array $f_ext is this:
124 * $f_ext['webspace']['allow']='';
125 * $f_ext['webspace']['deny']= PHP_EXTENSIONS_DEFAULT;
126 * $f_ext['ftpspace']['allow']='*';
127 * $f_ext['ftpspace']['deny']='';
128 * The control of fileextensions goes in two catagories. Webspace and Ftpspace. Webspace is folders accessible from a webbrowser (below TYPO3_DOCUMENT_ROOT) and ftpspace is everything else.
129 * The control is done like this: If an extension matches 'allow' then the check returns TRUE. If not and an extension matches 'deny' then the check return FALSE. If no match at all, returns TRUE.
130 * You list extensions comma-separated. If the value is a '*' every extension is allowed
131 * The list is case-insensitive when used in this class (see init())
132 * Typically TYPO3_CONF_VARS['BE']['fileExtensions'] would be passed along as $f_ext.
133 *
134 * Example:
135 * $basicff->init(array(), $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']);
136 *
137 * @param array Not in use anymore
138 * @param array Array with information about allowed and denied file extensions. Typically passed: $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']
139 * @return void
140 * @see typo3/init.php
141 */
142 public function init($mounts, $f_ext) {
143 $this->f_ext['webspace']['allow'] = GeneralUtility::uniqueList(strtolower($f_ext['webspace']['allow']));
144 $this->f_ext['webspace']['deny'] = GeneralUtility::uniqueList(strtolower($f_ext['webspace']['deny']));
145 $this->f_ext['ftpspace']['allow'] = GeneralUtility::uniqueList(strtolower($f_ext['ftpspace']['allow']));
146 $this->f_ext['ftpspace']['deny'] = GeneralUtility::uniqueList(strtolower($f_ext['ftpspace']['deny']));
147
148 $this->mounts = (!empty($mounts) ? $mounts : array());
149 $this->webPath = GeneralUtility::getIndpEnv('TYPO3_DOCUMENT_ROOT');
150 $this->isInit = 1;
151 $this->maxInputNameLen = $GLOBALS['TYPO3_CONF_VARS']['SYS']['maxFileNameLength'] ?: $this->maxInputNameLen;
152 }
153
154 /**
155 * Checks if a $iconkey (fileextension) is allowed according to $this->f_ext.
156 *
157 * @param string The extension to check, eg. "php" or "html" etc.
158 * @param string Either "webspage" or "ftpspace" - points to a key in $this->f_ext
159 * @return bool TRUE if file extension is allowed.
160 * @todo Deprecate, but still in use by checkIfAllowed()
161 * @deprecated but still in use in the Core. Don't use in your extensions!
162 */
163 public function is_allowed($iconkey, $type) {
164 if (isset($this->f_ext[$type])) {
165 $ik = strtolower($iconkey);
166 if ($ik) {
167 // If the extension is found amongst the allowed types, we return TRUE immediately
168 if ($this->f_ext[$type]['allow'] == '*' || GeneralUtility::inList($this->f_ext[$type]['allow'], $ik)) {
169 return TRUE;
170 }
171 // If the extension is found amongst the denied types, we return FALSE immediately
172 if ($this->f_ext[$type]['deny'] == '*' || GeneralUtility::inList($this->f_ext[$type]['deny'], $ik)) {
173 return FALSE;
174 }
175 // If no match we return TRUE
176 return TRUE;
177 } else {
178 // If no extension:
179 if ($this->f_ext[$type]['allow'] == '*') {
180 return TRUE;
181 }
182 if ($this->f_ext[$type]['deny'] == '*') {
183 return FALSE;
184 }
185 return TRUE;
186 }
187 }
188 return FALSE;
189 }
190
191 /**
192 * Returns TRUE if you can operate of ANY file ('*') in the space $theDest is in ('webspace' / 'ftpspace')
193 *
194 * @param string Absolute path
195 * @return bool
196 * @todo Deprecate: but still in use by through func_unzip in ExtendedFileUtility
197 * @deprecated but still in use in the Core. Don't use in your extensions!
198 */
199 public function checkIfFullAccess($theDest) {
200 $type = $this->is_webpath($theDest) ? 'webspace' : 'ftpspace';
201 if (isset($this->f_ext[$type])) {
202 if ((string)$this->f_ext[$type]['deny'] == '' || $this->f_ext[$type]['allow'] == '*') {
203 return TRUE;
204 }
205 }
206 }
207
208 /**
209 * Checks if $this->webPath (should be TYPO3_DOCUMENT_ROOT) is in the first part of $path
210 * Returns TRUE also if $this->init is not set or if $path is empty...
211 *
212 * @param string Absolute path to check
213 * @return bool
214 * @todo Deprecate, but still in use by DataHandler
215 * @deprecated but still in use in the Core. Don't use in your extensions!
216 */
217 public function is_webpath($path) {
218 if ($this->isInit) {
219 $testPath = $this->slashPath($path);
220 $testPathWeb = $this->slashPath($this->webPath);
221 if ($testPathWeb && $testPath) {
222 return GeneralUtility::isFirstPartOfStr($testPath, $testPathWeb);
223 }
224 }
225 return TRUE;
226 }
227
228 /**
229 * If the filename is given, check it against the TYPO3_CONF_VARS[BE][fileDenyPattern] +
230 * Checks if the $ext fileextension is allowed in the path $theDest (this is based on whether $theDest is below the $this->webPath)
231 *
232 * @param string File extension, eg. "php" or "html
233 * @param string Absolute path for which to test
234 * @param string Filename to check against TYPO3_CONF_VARS[BE][fileDenyPattern]
235 * @return bool TRUE if extension/filename is allowed
236 * @todo Deprecate, but still in use by DataHandler
237 * @deprecated but still in use in the Core. Don't use in your extensions!
238 */
239 public function checkIfAllowed($ext, $theDest, $filename = '') {
240 return GeneralUtility::verifyFilenameAgainstDenyPattern($filename) && $this->is_allowed($ext, ($this->is_webpath($theDest) ? 'webspace' : 'ftpspace'));
241 }
242
243 /**
244 * Cleans $theDir for slashes in the end of the string and returns the new path, if it exists on the server.
245 *
246 * @param string Directory path to check
247 * @return string Returns the cleaned up directory name if OK, otherwise FALSE.
248 * @todo Deprecate: but still in use by getUniqueName (used by DataHandler)
249 * @deprecated but still in use in the Core. Don't use in your extensions!
250 */
251 public function is_directory($theDir) {
252 // @todo: should go into the LocalDriver in a protected way (not important to the outside world)
253 if (GeneralUtility::validPathStr($theDir)) {
254 $theDir = PathUtility::getCanonicalPath($theDir);
255 if (@is_dir($theDir)) {
256 return $theDir;
257 }
258 }
259 return FALSE;
260 }
261
262 /**
263 * Returns the destination path/filename of a unique filename/foldername in that path.
264 * If $theFile exists in $theDest (directory) the file have numbers appended up to $this->maxNumber. Hereafter a unique string will be appended.
265 * This function is used by fx. TCEmain when files are attached to records and needs to be uniquely named in the uploads/* folders
266 *
267 * @param string The input filename to check
268 * @param string The directory for which to return a unique filename for $theFile. $theDest MUST be a valid directory. Should be absolute.
269 * @param bool If set the filename is returned with the path prepended without checking whether it already existed!
270 * @return string The destination absolute filepath (not just the name!) of a unique filename/foldername in that path.
271 * @see \TYPO3\CMS\Core\DataHandling\DataHandler::checkValue()
272 * @todo Deprecate, but still in use by the Core (DataHandler...)
273 * @deprecated but still in use in the Core. Don't use in your extensions!
274 */
275 public function getUniqueName($theFile, $theDest, $dontCheckForUnique = 0) {
276 // @todo: should go into the LocalDriver in a protected way (not important to the outside world)
277 $theDest = $this->is_directory($theDest);
278 // $theDest is cleaned up
279 $origFileInfo = GeneralUtility::split_fileref($theFile);
280 // Fetches info about path, name, extension of $theFile
281 if ($theDest) {
282 if ($this->getUniqueNamePrefix) {
283 // Adds prefix
284 $origFileInfo['file'] = $this->getUniqueNamePrefix . $origFileInfo['file'];
285 $origFileInfo['filebody'] = $this->getUniqueNamePrefix . $origFileInfo['filebody'];
286 }
287 // Check if the file exists and if not - return the filename...
288 $fileInfo = $origFileInfo;
289 $theDestFile = $theDest . '/' . $fileInfo['file'];
290 // The destinations file
291 if (!file_exists($theDestFile) || $dontCheckForUnique) {
292 // If the file does NOT exist we return this filename
293 return $theDestFile;
294 }
295 // Well the filename in its pure form existed. Now we try to append numbers / unique-strings and see if we can find an available filename...
296 $theTempFileBody = preg_replace('/_[0-9][0-9]$/', '', $origFileInfo['filebody']);
297 // This removes _xx if appended to the file
298 $theOrigExt = $origFileInfo['realFileext'] ? '.' . $origFileInfo['realFileext'] : '';
299 for ($a = 1; $a <= $this->maxNumber + 1; $a++) {
300 if ($a <= $this->maxNumber) {
301 // First we try to append numbers
302 $insert = '_' . sprintf('%02d', $a);
303 } else {
304 // .. then we try unique-strings...
305 $insert = '_' . substr(md5(uniqid('', TRUE)), 0, $this->uniquePrecision);
306 }
307 $theTestFile = $theTempFileBody . $insert . $theOrigExt;
308 $theDestFile = $theDest . '/' . $theTestFile;
309 // The destinations file
310 if (!file_exists($theDestFile)) {
311 // If the file does NOT exist we return this filename
312 return $theDestFile;
313 }
314 }
315 }
316 }
317
318 /**
319 * Checks if $thePath is a path under one of the paths in $this->mounts
320 * See comment in the header of this class.
321 *
322 * @param string $thePath MUST HAVE a trailing '/' in order to match correctly with the mounts
323 * @return string The key to the first mount found, otherwise nothing is returned.
324 * @see init()
325 * @todo: deprecate this function, now done in the Storage object. But still in use by impexp and ElementBrowser
326 * @deprecated but still in use in the Core. Don't use in your extensions!
327 */
328 public function checkPathAgainstMounts($thePath) {
329 if ($thePath && GeneralUtility::validPathStr($thePath) && is_array($this->mounts)) {
330 foreach ($this->mounts as $k => $val) {
331 if (GeneralUtility::isFirstPartOfStr($thePath, $val['path'])) {
332 return $k;
333 }
334 }
335 }
336 }
337
338 /**
339 * Find first web folder (relative to PATH_site.'fileadmin') in filemounts array
340 *
341 * @return string The key to the first mount inside PATH_site."fileadmin" found, otherwise nothing is returned.
342 * @todo: deprecate this function. But still in use by impexp
343 * @deprecated but still in use in the Core. Don't use in your extensions!
344 */
345 public function findFirstWebFolder() {
346 // @todo: where and when to use this function?
347 if (is_array($this->mounts)) {
348 foreach ($this->mounts as $k => $val) {
349 if (GeneralUtility::isFirstPartOfStr($val['path'], PATH_site . $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'])) {
350 return $k;
351 }
352 }
353 }
354 }
355
356 /*********************
357 *
358 * Cleaning functions
359 *
360 *********************/
361 /**
362 * Returns a string which has a slash '/' appended if it doesn't already have that slash
363 *
364 * @param string Input string
365 * @return string Output string with a slash in the end (if not already there)
366 * @todo Deprecate, but still in use by is_webpath, used by DataHandler
367 * @deprecated but still in use in the Core. Don't use in your extensions!
368 */
369 public function slashPath($path) {
370 // @todo: should go into the LocalDriver in a protected way (not important to the outside world)
371 // @todo: should be done with rtrim($path, '/') . '/';
372 if (substr($path, -1) != '/') {
373 return $path . '/';
374 }
375 return $path;
376 }
377
378 /**
379 * Returns a string where any character not matching [.a-zA-Z0-9_-] is substituted by '_'
380 * Trailing dots are removed
381 *
382 * @param string $fileName Input string, typically the body of a filename
383 * @param string $charset Charset of the a filename (defaults to current charset; depending on context)
384 * @return string Output string with any characters not matching [.a-zA-Z0-9_-] is substituted by '_' and trailing dots removed
385 * @todo Deprecate, but still in use by the core
386 * @deprecated but still in use in the Core. Don't use in your extensions!
387 */
388 public function cleanFileName($fileName, $charset = '') {
389 // Handle UTF-8 characters
390 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
391 // allow ".", "-", 0-9, a-z, A-Z and everything beyond U+C0 (latin capital letter a with grave)
392 $cleanFileName = preg_replace('/[' . self::UNSAFE_FILENAME_CHARACTER_EXPRESSION . ']/u', '_', trim($fileName));
393 } else {
394 // Get conversion object or initialize if needed
395 if (!is_object($this->csConvObj)) {
396 if (TYPO3_MODE == 'FE') {
397 $this->csConvObj = $GLOBALS['TSFE']->csConvObj;
398 } elseif (is_object($GLOBALS['LANG'])) {
399 // BE assumed:
400 $this->csConvObj = $GLOBALS['LANG']->csConvObj;
401 } else {
402 // The object may not exist yet, so we need to create it now. Happens in the Install Tool for example.
403 $this->csConvObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Charset\CharsetConverter::class);
404 }
405 }
406 // Define character set
407 if (!$charset) {
408 if (TYPO3_MODE == 'FE') {
409 $charset = $GLOBALS['TSFE']->renderCharset;
410 } else {
411 // Backend
412 $charset = 'utf-8';
413 }
414 }
415 // If a charset was found, convert filename
416 if ($charset) {
417 $fileName = $this->csConvObj->specCharsToASCII($charset, $fileName);
418 }
419 // Replace unwanted characters by underscores
420 $cleanFileName = preg_replace('/[' . self::UNSAFE_FILENAME_CHARACTER_EXPRESSION . '\\xC0-\\xFF]/', '_', trim($fileName));
421 }
422 // Strip trailing dots and return
423 return rtrim($cleanFileName, '.');
424 }
425
426 }