[TASK] Update php-cs-fixer to 2.5.0
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Resource / Driver / LocalDriver.php
1 <?php
2 namespace TYPO3\CMS\Core\Resource\Driver;
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\Resource\Exception;
18 use TYPO3\CMS\Core\Resource\FolderInterface;
19 use TYPO3\CMS\Core\Resource\ResourceStorage;
20 use TYPO3\CMS\Core\Type\File\FileInfo;
21 use TYPO3\CMS\Core\Utility\GeneralUtility;
22 use TYPO3\CMS\Core\Utility\PathUtility;
23
24 /**
25 * Driver for the local file system
26 */
27 class LocalDriver extends AbstractHierarchicalFilesystemDriver
28 {
29 /**
30 * @var string
31 */
32 const UNSAFE_FILENAME_CHARACTER_EXPRESSION = '\\x00-\\x2C\\/\\x3A-\\x3F\\x5B-\\x60\\x7B-\\xBF';
33
34 /**
35 * The absolute base path. It always contains a trailing slash.
36 *
37 * @var string
38 */
39 protected $absoluteBasePath;
40
41 /**
42 * A list of all supported hash algorithms, written all lower case.
43 *
44 * @var array
45 */
46 protected $supportedHashAlgorithms = ['sha1', 'md5'];
47
48 /**
49 * The base URL that points to this driver's storage. As long is this
50 * is not set, it is assumed that this folder is not publicly available
51 *
52 * @var string
53 */
54 protected $baseUri = null;
55
56 /** @var array */
57 protected $mappingFolderNameToRole = [
58 '_recycler_' => FolderInterface::ROLE_RECYCLER,
59 '_temp_' => FolderInterface::ROLE_TEMPORARY,
60 'user_upload' => FolderInterface::ROLE_USERUPLOAD,
61 ];
62
63 /**
64 * @param array $configuration
65 */
66 public function __construct(array $configuration = [])
67 {
68 parent::__construct($configuration);
69 // The capabilities default of this driver. See CAPABILITY_* constants for possible values
70 $this->capabilities =
71 ResourceStorage::CAPABILITY_BROWSABLE
72 | ResourceStorage::CAPABILITY_PUBLIC
73 | ResourceStorage::CAPABILITY_WRITABLE;
74 }
75
76 /**
77 * Merges the capabilites merged by the user at the storage
78 * configuration into the actual capabilities of the driver
79 * and returns the result.
80 *
81 * @param int $capabilities
82 * @return int
83 */
84 public function mergeConfigurationCapabilities($capabilities)
85 {
86 $this->capabilities &= $capabilities;
87 return $this->capabilities;
88 }
89
90 /**
91 * Processes the configuration for this driver.
92 */
93 public function processConfiguration()
94 {
95 $this->absoluteBasePath = $this->calculateBasePath($this->configuration);
96 $this->determineBaseUrl();
97 if ($this->baseUri === null) {
98 // remove public flag
99 $this->capabilities &= ~ResourceStorage::CAPABILITY_PUBLIC;
100 }
101 }
102
103 /**
104 * Initializes this object. This is called by the storage after the driver
105 * has been attached.
106 */
107 public function initialize()
108 {
109 }
110
111 /**
112 * Determines the base URL for this driver, from the configuration or
113 * the TypoScript frontend object
114 */
115 protected function determineBaseUrl()
116 {
117 // only calculate baseURI if the storage does not enforce jumpUrl Script
118 if ($this->hasCapability(ResourceStorage::CAPABILITY_PUBLIC)) {
119 if (GeneralUtility::isFirstPartOfStr($this->absoluteBasePath, PATH_site)) {
120 // use site-relative URLs
121 $temporaryBaseUri = rtrim(PathUtility::stripPathSitePrefix($this->absoluteBasePath), '/');
122 if ($temporaryBaseUri !== '') {
123 $uriParts = explode('/', $temporaryBaseUri);
124 $uriParts = array_map('rawurlencode', $uriParts);
125 $temporaryBaseUri = implode('/', $uriParts) . '/';
126 }
127 $this->baseUri = $temporaryBaseUri;
128 } elseif (isset($this->configuration['baseUri']) && GeneralUtility::isValidUrl($this->configuration['baseUri'])) {
129 $this->baseUri = rtrim($this->configuration['baseUri'], '/') . '/';
130 }
131 }
132 }
133
134 /**
135 * Calculates the absolute path to this drivers storage location.
136 *
137 * @throws Exception\InvalidConfigurationException
138 * @param array $configuration
139 * @return string
140 */
141 protected function calculateBasePath(array $configuration)
142 {
143 if (!array_key_exists('basePath', $configuration) || empty($configuration['basePath'])) {
144 throw new Exception\InvalidConfigurationException(
145 'Configuration must contain base path.',
146 1346510477
147 );
148 }
149
150 if ($configuration['pathType'] === 'relative') {
151 $relativeBasePath = $configuration['basePath'];
152 $absoluteBasePath = PATH_site . $relativeBasePath;
153 } else {
154 $absoluteBasePath = $configuration['basePath'];
155 }
156 $absoluteBasePath = $this->canonicalizeAndCheckFilePath($absoluteBasePath);
157 $absoluteBasePath = rtrim($absoluteBasePath, '/') . '/';
158 if (!is_dir($absoluteBasePath)) {
159 throw new Exception\InvalidConfigurationException(
160 'Base path "' . $absoluteBasePath . '" does not exist or is no directory.',
161 1299233097
162 );
163 }
164 return $absoluteBasePath;
165 }
166
167 /**
168 * Returns the public URL to a file.
169 * For the local driver, this will always return a path relative to PATH_site.
170 *
171 * @param string $identifier
172 * @return string
173 * @throws \TYPO3\CMS\Core\Resource\Exception
174 */
175 public function getPublicUrl($identifier)
176 {
177 $publicUrl = null;
178 if ($this->baseUri !== null) {
179 $uriParts = explode('/', ltrim($identifier, '/'));
180 $uriParts = array_map('rawurlencode', $uriParts);
181 $identifier = implode('/', $uriParts);
182 $publicUrl = $this->baseUri . $identifier;
183 }
184 return $publicUrl;
185 }
186
187 /**
188 * Returns the Identifier of the root level folder of the storage.
189 *
190 * @return string
191 */
192 public function getRootLevelFolder()
193 {
194 return '/';
195 }
196
197 /**
198 * Returns identifier of the default folder new files should be put into.
199 *
200 * @return string
201 */
202 public function getDefaultFolder()
203 {
204 $identifier = '/user_upload/';
205 $createFolder = !$this->folderExists($identifier);
206 if ($createFolder === true) {
207 $identifier = $this->createFolder('user_upload');
208 }
209 return $identifier;
210 }
211
212 /**
213 * Creates a folder, within a parent folder.
214 * If no parent folder is given, a rootlevel folder will be created
215 *
216 * @param string $newFolderName
217 * @param string $parentFolderIdentifier
218 * @param bool $recursive
219 * @return string the Identifier of the new folder
220 */
221 public function createFolder($newFolderName, $parentFolderIdentifier = '', $recursive = false)
222 {
223 $parentFolderIdentifier = $this->canonicalizeAndCheckFolderIdentifier($parentFolderIdentifier);
224 $newFolderName = trim($newFolderName, '/');
225 if ($recursive == false) {
226 $newFolderName = $this->sanitizeFileName($newFolderName);
227 $newIdentifier = $parentFolderIdentifier . $newFolderName . '/';
228 GeneralUtility::mkdir($this->getAbsolutePath($newIdentifier));
229 } else {
230 $parts = GeneralUtility::trimExplode('/', $newFolderName);
231 $parts = array_map([$this, 'sanitizeFileName'], $parts);
232 $newFolderName = implode('/', $parts);
233 $newIdentifier = $parentFolderIdentifier . $newFolderName . '/';
234 GeneralUtility::mkdir_deep($this->getAbsolutePath($parentFolderIdentifier) . '/', $newFolderName);
235 }
236 return $newIdentifier;
237 }
238
239 /**
240 * Returns information about a file.
241 *
242 * @param string $fileIdentifier In the case of the LocalDriver, this is the (relative) path to the file.
243 * @param array $propertiesToExtract Array of properties which should be extracted, if empty all will be extracted
244 * @return array
245 * @throws \InvalidArgumentException
246 */
247 public function getFileInfoByIdentifier($fileIdentifier, array $propertiesToExtract = [])
248 {
249 $absoluteFilePath = $this->getAbsolutePath($fileIdentifier);
250 // don't use $this->fileExists() because we need the absolute path to the file anyways, so we can directly
251 // use PHP's filesystem method.
252 if (!file_exists($absoluteFilePath) || !is_file($absoluteFilePath)) {
253 throw new \InvalidArgumentException('File ' . $fileIdentifier . ' does not exist.', 1314516809);
254 }
255
256 $dirPath = PathUtility::dirname($fileIdentifier);
257 $dirPath = $this->canonicalizeAndCheckFolderIdentifier($dirPath);
258 return $this->extractFileInformation($absoluteFilePath, $dirPath, $propertiesToExtract);
259 }
260
261 /**
262 * Returns information about a folder.
263 *
264 * @param string $folderIdentifier In the case of the LocalDriver, this is the (relative) path to the file.
265 * @return array
266 * @throws Exception\FolderDoesNotExistException
267 */
268 public function getFolderInfoByIdentifier($folderIdentifier)
269 {
270 $folderIdentifier = $this->canonicalizeAndCheckFolderIdentifier($folderIdentifier);
271
272 if (!$this->folderExists($folderIdentifier)) {
273 throw new Exception\FolderDoesNotExistException(
274 'Folder "' . $folderIdentifier . '" does not exist.',
275 1314516810
276 );
277 }
278 $absolutePath = $this->getAbsolutePath($folderIdentifier);
279 return [
280 'identifier' => $folderIdentifier,
281 'name' => PathUtility::basename($folderIdentifier),
282 'mtime' => filemtime($absolutePath),
283 'ctime' => filectime($absolutePath),
284 'storage' => $this->storageUid
285 ];
286 }
287
288 /**
289 * Returns a string where any character not matching [.a-zA-Z0-9_-] is
290 * substituted by '_'
291 * Trailing dots are removed
292 *
293 * Previously in \TYPO3\CMS\Core\Utility\File\BasicFileUtility::cleanFileName()
294 *
295 * @param string $fileName Input string, typically the body of a fileName
296 * @param string $charset Charset of the a fileName (defaults to utf-8)
297 * @return string Output string with any characters not matching [.a-zA-Z0-9_-] is substituted by '_' and trailing dots removed
298 * @throws Exception\InvalidFileNameException
299 */
300 public function sanitizeFileName($fileName, $charset = 'utf-8')
301 {
302 // Handle UTF-8 characters
303 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
304 // Allow ".", "-", 0-9, a-z, A-Z and everything beyond U+C0 (latin capital letter a with grave)
305 $cleanFileName = preg_replace('/[' . self::UNSAFE_FILENAME_CHARACTER_EXPRESSION . ']/u', '_', trim($fileName));
306 } else {
307 $fileName = $this->getCharsetConversion()->specCharsToASCII($charset, $fileName);
308 // Replace unwanted characters by underscores
309 $cleanFileName = preg_replace('/[' . self::UNSAFE_FILENAME_CHARACTER_EXPRESSION . '\\xC0-\\xFF]/', '_', trim($fileName));
310 }
311 // Strip trailing dots and return
312 $cleanFileName = rtrim($cleanFileName, '.');
313 if ($cleanFileName === '') {
314 throw new Exception\InvalidFileNameException(
315 'File name ' . $fileName . ' is invalid.',
316 1320288991
317 );
318 }
319 return $cleanFileName;
320 }
321
322 /**
323 * Generic wrapper for extracting a list of items from a path.
324 *
325 * @param string $folderIdentifier
326 * @param int $start The position to start the listing; if not set, start from the beginning
327 * @param int $numberOfItems The number of items to list; if set to zero, all items are returned
328 * @param array $filterMethods The filter methods used to filter the directory items
329 * @param bool $includeFiles
330 * @param bool $includeDirs
331 * @param bool $recursive
332 * @param string $sort Property name used to sort the items.
333 * Among them may be: '' (empty, no sorting), name,
334 * fileext, size, tstamp and rw.
335 * If a driver does not support the given property, it
336 * should fall back to "name".
337 * @param bool $sortRev TRUE to indicate reverse sorting (last to first)
338 * @return array
339 * @throws \InvalidArgumentException
340 */
341 protected function getDirectoryItemList($folderIdentifier, $start = 0, $numberOfItems = 0, array $filterMethods, $includeFiles = true, $includeDirs = true, $recursive = false, $sort = '', $sortRev = false)
342 {
343 $folderIdentifier = $this->canonicalizeAndCheckFolderIdentifier($folderIdentifier);
344 $realPath = $this->getAbsolutePath($folderIdentifier);
345 if (!is_dir($realPath)) {
346 throw new \InvalidArgumentException(
347 'Cannot list items in directory ' . $folderIdentifier . ' - does not exist or is no directory',
348 1314349666
349 );
350 }
351
352 $items = $this->retrieveFileAndFoldersInPath($realPath, $recursive, $includeFiles, $includeDirs, $sort, $sortRev);
353 $iterator = new \ArrayIterator($items);
354 if ($iterator->count() === 0) {
355 return [];
356 }
357
358 // $c is the counter for how many items we still have to fetch (-1 is unlimited)
359 $c = $numberOfItems > 0 ? $numberOfItems : - 1;
360 $items = [];
361 while ($iterator->valid() && ($numberOfItems === 0 || $c > 0)) {
362 // $iteratorItem is the file or folder name
363 $iteratorItem = $iterator->current();
364 // go on to the next iterator item now as we might skip this one early
365 $iterator->next();
366
367 try {
368 if (
369 !$this->applyFilterMethodsToDirectoryItem(
370 $filterMethods,
371 $iteratorItem['name'],
372 $iteratorItem['identifier'],
373 $this->getParentFolderIdentifierOfIdentifier($iteratorItem['identifier'])
374 )
375 ) {
376 continue;
377 }
378 if ($start > 0) {
379 $start--;
380 } else {
381 $items[$iteratorItem['identifier']] = $iteratorItem['identifier'];
382 // Decrement item counter to make sure we only return $numberOfItems
383 // we cannot do this earlier in the method (unlike moving the iterator forward) because we only add the
384 // item here
385 --$c;
386 }
387 } catch (Exception\InvalidPathException $e) {
388 }
389 }
390 return $items;
391 }
392
393 /**
394 * Applies a set of filter methods to a file name to find out if it should be used or not. This is e.g. used by
395 * directory listings.
396 *
397 * @param array $filterMethods The filter methods to use
398 * @param string $itemName
399 * @param string $itemIdentifier
400 * @param string $parentIdentifier
401 * @throws \RuntimeException
402 * @return bool
403 */
404 protected function applyFilterMethodsToDirectoryItem(array $filterMethods, $itemName, $itemIdentifier, $parentIdentifier)
405 {
406 foreach ($filterMethods as $filter) {
407 if (is_callable($filter)) {
408 $result = call_user_func($filter, $itemName, $itemIdentifier, $parentIdentifier, [], $this);
409 // We have to use -1 as the „don't include“ return value, as call_user_func() will return FALSE
410 // If calling the method succeeded and thus we can't use that as a return value.
411 if ($result === -1) {
412 return false;
413 }
414 if ($result === false) {
415 throw new \RuntimeException(
416 'Could not apply file/folder name filter ' . $filter[0] . '::' . $filter[1],
417 1476046425
418 );
419 }
420 }
421 }
422 return true;
423 }
424
425 /**
426 * Returns a file inside the specified path
427 *
428 * @param string $fileName
429 * @param string $folderIdentifier
430 * @return string File Identifier
431 */
432 public function getFileInFolder($fileName, $folderIdentifier)
433 {
434 return $this->canonicalizeAndCheckFileIdentifier($folderIdentifier . '/' . $fileName);
435 }
436
437 /**
438 * Returns a list of files inside the specified path
439 *
440 * @param string $folderIdentifier
441 * @param int $start
442 * @param int $numberOfItems
443 * @param bool $recursive
444 * @param array $filenameFilterCallbacks The method callbacks to use for filtering the items
445 * @param string $sort Property name used to sort the items.
446 * Among them may be: '' (empty, no sorting), name,
447 * fileext, size, tstamp and rw.
448 * If a driver does not support the given property, it
449 * should fall back to "name".
450 * @param bool $sortRev TRUE to indicate reverse sorting (last to first)
451 * @return array of FileIdentifiers
452 */
453 public function getFilesInFolder($folderIdentifier, $start = 0, $numberOfItems = 0, $recursive = false, array $filenameFilterCallbacks = [], $sort = '', $sortRev = false)
454 {
455 return $this->getDirectoryItemList($folderIdentifier, $start, $numberOfItems, $filenameFilterCallbacks, true, false, $recursive, $sort, $sortRev);
456 }
457
458 /**
459 * Returns the number of files inside the specified path
460 *
461 * @param string $folderIdentifier
462 * @param bool $recursive
463 * @param array $filenameFilterCallbacks callbacks for filtering the items
464 * @return int Number of files in folder
465 */
466 public function countFilesInFolder($folderIdentifier, $recursive = false, array $filenameFilterCallbacks = [])
467 {
468 return count($this->getFilesInFolder($folderIdentifier, 0, 0, $recursive, $filenameFilterCallbacks));
469 }
470
471 /**
472 * Returns a list of folders inside the specified path
473 *
474 * @param string $folderIdentifier
475 * @param int $start
476 * @param int $numberOfItems
477 * @param bool $recursive
478 * @param array $folderNameFilterCallbacks The method callbacks to use for filtering the items
479 * @param string $sort Property name used to sort the items.
480 * Among them may be: '' (empty, no sorting), name,
481 * fileext, size, tstamp and rw.
482 * If a driver does not support the given property, it
483 * should fall back to "name".
484 * @param bool $sortRev TRUE to indicate reverse sorting (last to first)
485 * @return array of Folder Identifier
486 */
487 public function getFoldersInFolder($folderIdentifier, $start = 0, $numberOfItems = 0, $recursive = false, array $folderNameFilterCallbacks = [], $sort = '', $sortRev = false)
488 {
489 return $this->getDirectoryItemList($folderIdentifier, $start, $numberOfItems, $folderNameFilterCallbacks, false, true, $recursive, $sort, $sortRev);
490 }
491
492 /**
493 * Returns the number of folders inside the specified path
494 *
495 * @param string $folderIdentifier
496 * @param bool $recursive
497 * @param array $folderNameFilterCallbacks callbacks for filtering the items
498 * @return int Number of folders in folder
499 */
500 public function countFoldersInFolder($folderIdentifier, $recursive = false, array $folderNameFilterCallbacks = [])
501 {
502 return count($this->getFoldersInFolder($folderIdentifier, 0, 0, $recursive, $folderNameFilterCallbacks));
503 }
504
505 /**
506 * Returns a list with the names of all files and folders in a path, optionally recursive.
507 *
508 * @param string $path The absolute path
509 * @param bool $recursive If TRUE, recursively fetches files and folders
510 * @param bool $includeFiles
511 * @param bool $includeDirs
512 * @param string $sort Property name used to sort the items.
513 * Among them may be: '' (empty, no sorting), name,
514 * fileext, size, tstamp and rw.
515 * If a driver does not support the given property, it
516 * should fall back to "name".
517 * @param bool $sortRev TRUE to indicate reverse sorting (last to first)
518 * @return array
519 */
520 protected function retrieveFileAndFoldersInPath($path, $recursive = false, $includeFiles = true, $includeDirs = true, $sort = '', $sortRev = false)
521 {
522 $pathLength = strlen($this->getAbsoluteBasePath());
523 $iteratorMode = \FilesystemIterator::UNIX_PATHS | \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::FOLLOW_SYMLINKS;
524 if ($recursive) {
525 $iterator = new \RecursiveIteratorIterator(
526 new \RecursiveDirectoryIterator($path, $iteratorMode),
527 \RecursiveIteratorIterator::SELF_FIRST,
528 \RecursiveIteratorIterator::CATCH_GET_CHILD
529 );
530 } else {
531 $iterator = new \RecursiveDirectoryIterator($path, $iteratorMode);
532 }
533
534 $directoryEntries = [];
535 while ($iterator->valid()) {
536 /** @var $entry \SplFileInfo */
537 $entry = $iterator->current();
538 // skip non-files/non-folders, and empty entries
539 if ((!$entry->isFile() && !$entry->isDir()) || $entry->getFilename() == '' ||
540 ($entry->isFile() && !$includeFiles) || ($entry->isDir() && !$includeDirs)) {
541 $iterator->next();
542 continue;
543 }
544 $entryIdentifier = '/' . substr($entry->getPathname(), $pathLength);
545 $entryName = PathUtility::basename($entryIdentifier);
546 if ($entry->isDir()) {
547 $entryIdentifier .= '/';
548 }
549 $entryArray = [
550 'identifier' => $entryIdentifier,
551 'name' => $entryName,
552 'type' => $entry->isDir() ? 'dir' : 'file'
553 ];
554 $directoryEntries[$entryIdentifier] = $entryArray;
555 $iterator->next();
556 }
557 return $this->sortDirectoryEntries($directoryEntries, $sort, $sortRev);
558 }
559
560 /**
561 * Sort the directory entries by a certain key
562 *
563 * @param array $directoryEntries Array of directory entry arrays from
564 * retrieveFileAndFoldersInPath()
565 * @param string $sort Property name used to sort the items.
566 * Among them may be: '' (empty, no sorting), name,
567 * fileext, size, tstamp and rw.
568 * If a driver does not support the given property, it
569 * should fall back to "name".
570 * @param bool $sortRev TRUE to indicate reverse sorting (last to first)
571 * @return array Sorted entries. Content of the keys is undefined.
572 */
573 protected function sortDirectoryEntries($directoryEntries, $sort = '', $sortRev = false)
574 {
575 $entriesToSort = [];
576 foreach ($directoryEntries as $entryArray) {
577 $dir = pathinfo($entryArray['name'], PATHINFO_DIRNAME) . '/';
578 $fullPath = $this->getAbsoluteBasePath() . $entryArray['identifier'];
579 switch ($sort) {
580 case 'size':
581 $sortingKey = '0';
582 if ($entryArray['type'] === 'file') {
583 $sortingKey = $this->getSpecificFileInformation($fullPath, $dir, 'size');
584 }
585 // Add a character for a natural order sorting
586 $sortingKey .= 's';
587 break;
588 case 'rw':
589 $perms = $this->getPermissions($entryArray['identifier']);
590 $sortingKey = ($perms['r'] ? 'R' : '')
591 . ($perms['w'] ? 'W' : '');
592 break;
593 case 'fileext':
594 $sortingKey = pathinfo($entryArray['name'], PATHINFO_EXTENSION);
595 break;
596 case 'tstamp':
597 $sortingKey = '0';
598 if ($entryArray['type'] === 'file') {
599 $sortingKey = $this->getSpecificFileInformation($fullPath, $dir, 'mtime');
600 }
601 // Add a character for a natural order sorting
602 $sortingKey .= 't';
603 break;
604 case 'name':
605 case 'file':
606 default:
607 $sortingKey = $entryArray['name'];
608 }
609 $i = 0;
610 while (isset($entriesToSort[$sortingKey . $i])) {
611 $i++;
612 }
613 $entriesToSort[$sortingKey . $i] = $entryArray;
614 }
615 uksort($entriesToSort, 'strnatcasecmp');
616
617 if ($sortRev) {
618 $entriesToSort = array_reverse($entriesToSort);
619 }
620
621 return $entriesToSort;
622 }
623
624 /**
625 * Extracts information about a file from the filesystem.
626 *
627 * @param string $filePath The absolute path to the file
628 * @param string $containerPath The relative path to the file's container
629 * @param array $propertiesToExtract array of properties which should be returned, if empty all will be extracted
630 * @return array
631 */
632 protected function extractFileInformation($filePath, $containerPath, array $propertiesToExtract = [])
633 {
634 if (empty($propertiesToExtract)) {
635 $propertiesToExtract = [
636 'size', 'atime', 'atime', 'mtime', 'ctime', 'mimetype', 'name',
637 'identifier', 'identifier_hash', 'storage', 'folder_hash'
638 ];
639 }
640 $fileInformation = [];
641 foreach ($propertiesToExtract as $property) {
642 $fileInformation[$property] = $this->getSpecificFileInformation($filePath, $containerPath, $property);
643 }
644 return $fileInformation;
645 }
646
647 /**
648 * Extracts a specific FileInformation from the FileSystems.
649 *
650 * @param string $fileIdentifier
651 * @param string $containerPath
652 * @param string $property
653 *
654 * @return bool|int|string
655 * @throws \InvalidArgumentException
656 */
657 public function getSpecificFileInformation($fileIdentifier, $containerPath, $property)
658 {
659 $identifier = $this->canonicalizeAndCheckFileIdentifier($containerPath . PathUtility::basename($fileIdentifier));
660
661 /** @var FileInfo $fileInfo */
662 $fileInfo = GeneralUtility::makeInstance(FileInfo::class, $fileIdentifier);
663 switch ($property) {
664 case 'size':
665 return $fileInfo->getSize();
666 case 'atime':
667 return $fileInfo->getATime();
668 case 'mtime':
669 return $fileInfo->getMTime();
670 case 'ctime':
671 return $fileInfo->getCTime();
672 case 'name':
673 return PathUtility::basename($fileIdentifier);
674 case 'mimetype':
675 return (string)$fileInfo->getMimeType();
676 case 'identifier':
677 return $identifier;
678 case 'storage':
679 return $this->storageUid;
680 case 'identifier_hash':
681 return $this->hashIdentifier($identifier);
682 case 'folder_hash':
683 return $this->hashIdentifier($this->getParentFolderIdentifierOfIdentifier($identifier));
684 default:
685 throw new \InvalidArgumentException(sprintf('The information "%s" is not available.', $property), 1476047422);
686 }
687 }
688
689 /**
690 * Returns the absolute path of the folder this driver operates on.
691 *
692 * @return string
693 */
694 protected function getAbsoluteBasePath()
695 {
696 return $this->absoluteBasePath;
697 }
698
699 /**
700 * Returns the absolute path of a file or folder.
701 *
702 * @param string $fileIdentifier
703 * @return string
704 * @throws Exception\InvalidPathException
705 */
706 protected function getAbsolutePath($fileIdentifier)
707 {
708 $relativeFilePath = ltrim($this->canonicalizeAndCheckFileIdentifier($fileIdentifier), '/');
709 $path = $this->absoluteBasePath . $relativeFilePath;
710 return $path;
711 }
712
713 /**
714 * Creates a (cryptographic) hash for a file.
715 *
716 * @param string $fileIdentifier
717 * @param string $hashAlgorithm The hash algorithm to use
718 * @return string
719 * @throws \RuntimeException
720 * @throws \InvalidArgumentException
721 */
722 public function hash($fileIdentifier, $hashAlgorithm)
723 {
724 if (!in_array($hashAlgorithm, $this->supportedHashAlgorithms)) {
725 throw new \InvalidArgumentException('Hash algorithm "' . $hashAlgorithm . '" is not supported.', 1304964032);
726 }
727 switch ($hashAlgorithm) {
728 case 'sha1':
729 $hash = sha1_file($this->getAbsolutePath($fileIdentifier));
730 break;
731 case 'md5':
732 $hash = md5_file($this->getAbsolutePath($fileIdentifier));
733 break;
734 default:
735 throw new \RuntimeException('Hash algorithm ' . $hashAlgorithm . ' is not implemented.', 1329644451);
736 }
737 return $hash;
738 }
739
740 /**
741 * Adds a file from the local server hard disk to a given path in TYPO3s virtual file system.
742 * This assumes that the local file exists, so no further check is done here!
743 * After a successful the original file must not exist anymore.
744 *
745 * @param string $localFilePath (within PATH_site)
746 * @param string $targetFolderIdentifier
747 * @param string $newFileName optional, if not given original name is used
748 * @param bool $removeOriginal if set the original file will be removed after successful operation
749 * @return string the identifier of the new file
750 * @throws \RuntimeException
751 * @throws \InvalidArgumentException
752 */
753 public function addFile($localFilePath, $targetFolderIdentifier, $newFileName = '', $removeOriginal = true)
754 {
755 $localFilePath = $this->canonicalizeAndCheckFilePath($localFilePath);
756 // as for the "virtual storage" for backwards-compatibility, this check always fails, as the file probably lies under PATH_site
757 // thus, it is not checked here
758 // @todo is check in storage
759 if (GeneralUtility::isFirstPartOfStr($localFilePath, $this->absoluteBasePath) && $this->storageUid > 0) {
760 throw new \InvalidArgumentException('Cannot add a file that is already part of this storage.', 1314778269);
761 }
762 $newFileName = $this->sanitizeFileName($newFileName !== '' ? $newFileName : PathUtility::basename($localFilePath));
763 $newFileIdentifier = $this->canonicalizeAndCheckFolderIdentifier($targetFolderIdentifier) . $newFileName;
764 $targetPath = $this->getAbsolutePath($newFileIdentifier);
765
766 if ($removeOriginal) {
767 if (is_uploaded_file($localFilePath)) {
768 $result = move_uploaded_file($localFilePath, $targetPath);
769 } else {
770 $result = rename($localFilePath, $targetPath);
771 }
772 } else {
773 $result = copy($localFilePath, $targetPath);
774 }
775 if ($result === false || !file_exists($targetPath)) {
776 throw new \RuntimeException(
777 'Adding file ' . $localFilePath . ' at ' . $newFileIdentifier . ' failed.',
778 1476046453
779 );
780 }
781 clearstatcache();
782 // Change the permissions of the file
783 GeneralUtility::fixPermissions($targetPath);
784 return $newFileIdentifier;
785 }
786
787 /**
788 * Checks if a file exists.
789 *
790 * @param string $fileIdentifier
791 *
792 * @return bool
793 */
794 public function fileExists($fileIdentifier)
795 {
796 $absoluteFilePath = $this->getAbsolutePath($fileIdentifier);
797 return is_file($absoluteFilePath);
798 }
799
800 /**
801 * Checks if a file inside a folder exists
802 *
803 * @param string $fileName
804 * @param string $folderIdentifier
805 * @return bool
806 */
807 public function fileExistsInFolder($fileName, $folderIdentifier)
808 {
809 $identifier = $folderIdentifier . '/' . $fileName;
810 $identifier = $this->canonicalizeAndCheckFileIdentifier($identifier);
811 return $this->fileExists($identifier);
812 }
813
814 /**
815 * Checks if a folder exists.
816 *
817 * @param string $folderIdentifier
818 *
819 * @return bool
820 */
821 public function folderExists($folderIdentifier)
822 {
823 $absoluteFilePath = $this->getAbsolutePath($folderIdentifier);
824 return is_dir($absoluteFilePath);
825 }
826
827 /**
828 * Checks if a folder inside a folder exists.
829 *
830 * @param string $folderName
831 * @param string $folderIdentifier
832 * @return bool
833 */
834 public function folderExistsInFolder($folderName, $folderIdentifier)
835 {
836 $identifier = $folderIdentifier . '/' . $folderName;
837 $identifier = $this->canonicalizeAndCheckFolderIdentifier($identifier);
838 return $this->folderExists($identifier);
839 }
840
841 /**
842 * Returns the Identifier for a folder within a given folder.
843 *
844 * @param string $folderName The name of the target folder
845 * @param string $folderIdentifier
846 * @return string
847 */
848 public function getFolderInFolder($folderName, $folderIdentifier)
849 {
850 $folderIdentifier = $this->canonicalizeAndCheckFolderIdentifier($folderIdentifier . '/' . $folderName);
851 return $folderIdentifier;
852 }
853
854 /**
855 * Replaces the contents (and file-specific metadata) of a file object with a local file.
856 *
857 * @param string $fileIdentifier
858 * @param string $localFilePath
859 * @return bool TRUE if the operation succeeded
860 * @throws \RuntimeException
861 */
862 public function replaceFile($fileIdentifier, $localFilePath)
863 {
864 $filePath = $this->getAbsolutePath($fileIdentifier);
865 if (is_uploaded_file($localFilePath)) {
866 $result = move_uploaded_file($localFilePath, $filePath);
867 } else {
868 $result = rename($localFilePath, $filePath);
869 }
870 GeneralUtility::fixPermissions($filePath);
871 if ($result === false) {
872 throw new \RuntimeException('Replacing file ' . $fileIdentifier . ' with ' . $localFilePath . ' failed.', 1315314711);
873 }
874 return $result;
875 }
876
877 /**
878 * Copies a file *within* the current storage.
879 * Note that this is only about an intra-storage copy action, where a file is just
880 * copied to another folder in the same storage.
881 *
882 * @param string $fileIdentifier
883 * @param string $targetFolderIdentifier
884 * @param string $fileName
885 * @return string the Identifier of the new file
886 */
887 public function copyFileWithinStorage($fileIdentifier, $targetFolderIdentifier, $fileName)
888 {
889 $sourcePath = $this->getAbsolutePath($fileIdentifier);
890 $newIdentifier = $targetFolderIdentifier . '/' . $fileName;
891 $newIdentifier = $this->canonicalizeAndCheckFileIdentifier($newIdentifier);
892
893 $absoluteFilePath = $this->getAbsolutePath($newIdentifier);
894 copy($sourcePath, $absoluteFilePath);
895 GeneralUtility::fixPermissions($absoluteFilePath);
896 return $newIdentifier;
897 }
898
899 /**
900 * Moves a file *within* the current storage.
901 * Note that this is only about an inner-storage move action, where a file is just
902 * moved to another folder in the same storage.
903 *
904 * @param string $fileIdentifier
905 * @param string $targetFolderIdentifier
906 * @param string $newFileName
907 * @return string
908 * @throws \RuntimeException
909 */
910 public function moveFileWithinStorage($fileIdentifier, $targetFolderIdentifier, $newFileName)
911 {
912 $sourcePath = $this->getAbsolutePath($fileIdentifier);
913 $targetIdentifier = $targetFolderIdentifier . '/' . $newFileName;
914 $targetIdentifier = $this->canonicalizeAndCheckFileIdentifier($targetIdentifier);
915 $result = rename($sourcePath, $this->getAbsolutePath($targetIdentifier));
916 if ($result === false) {
917 throw new \RuntimeException('Moving file ' . $sourcePath . ' to ' . $targetIdentifier . ' failed.', 1315314712);
918 }
919 return $targetIdentifier;
920 }
921
922 /**
923 * Copies a file to a temporary path and returns that path.
924 *
925 * @param string $fileIdentifier
926 * @return string The temporary path
927 * @throws \RuntimeException
928 */
929 protected function copyFileToTemporaryPath($fileIdentifier)
930 {
931 $sourcePath = $this->getAbsolutePath($fileIdentifier);
932 $temporaryPath = $this->getTemporaryPathForFile($fileIdentifier);
933 $result = copy($sourcePath, $temporaryPath);
934 touch($temporaryPath, filemtime($sourcePath));
935 if ($result === false) {
936 throw new \RuntimeException(
937 'Copying file "' . $fileIdentifier . '" to temporary path "' . $temporaryPath . '" failed.',
938 1320577649
939 );
940 }
941 return $temporaryPath;
942 }
943
944 /**
945 * Moves a file or folder to the given directory, renaming the source in the process if
946 * a file or folder of the same name already exists in the target path.
947 *
948 * @param string $filePath
949 * @param string $recycleDirectory
950 * @return bool
951 */
952 protected function recycleFileOrFolder($filePath, $recycleDirectory)
953 {
954 $destinationFile = $recycleDirectory . '/' . PathUtility::basename($filePath);
955 if (file_exists($destinationFile)) {
956 $timeStamp = \DateTimeImmutable::createFromFormat('U.u', microtime(true))->format('YmdHisu');
957 $destinationFile = $recycleDirectory . '/' . $timeStamp . '_' . PathUtility::basename($filePath);
958 }
959 $result = rename($filePath, $destinationFile);
960 // Update the mtime for the file, so the recycler garbage collection task knows which files to delete
961 // Using ctime() is not possible there since this is not supported on Windows
962 if ($result) {
963 touch($destinationFile);
964 }
965 return $result;
966 }
967
968 /**
969 * Creates a map of old and new file/folder identifiers after renaming or
970 * moving a folder. The old identifier is used as the key, the new one as the value.
971 *
972 * @param array $filesAndFolders
973 * @param string $sourceFolderIdentifier
974 * @param string $targetFolderIdentifier
975 *
976 * @return array
977 * @throws Exception\FileOperationErrorException
978 */
979 protected function createIdentifierMap(array $filesAndFolders, $sourceFolderIdentifier, $targetFolderIdentifier)
980 {
981 $identifierMap = [];
982 $identifierMap[$sourceFolderIdentifier] = $targetFolderIdentifier;
983 foreach ($filesAndFolders as $oldItem) {
984 if ($oldItem['type'] === 'dir') {
985 $oldIdentifier = $oldItem['identifier'];
986 $newIdentifier = $this->canonicalizeAndCheckFolderIdentifier(
987 str_replace($sourceFolderIdentifier, $targetFolderIdentifier, $oldItem['identifier'])
988 );
989 } else {
990 $oldIdentifier = $oldItem['identifier'];
991 $newIdentifier = $this->canonicalizeAndCheckFileIdentifier(
992 str_replace($sourceFolderIdentifier, $targetFolderIdentifier, $oldItem['identifier'])
993 );
994 }
995 if (!file_exists($this->getAbsolutePath($newIdentifier))) {
996 throw new Exception\FileOperationErrorException(
997 sprintf('File "%1$s" was not found (should have been copied/moved from "%2$s").', $newIdentifier, $oldIdentifier),
998 1330119453
999 );
1000 }
1001 $identifierMap[$oldIdentifier] = $newIdentifier;
1002 }
1003 return $identifierMap;
1004 }
1005
1006 /**
1007 * Folder equivalent to moveFileWithinStorage().
1008 *
1009 * @param string $sourceFolderIdentifier
1010 * @param string $targetFolderIdentifier
1011 * @param string $newFolderName
1012 *
1013 * @return array A map of old to new file identifiers
1014 * @throws \RuntimeException
1015 */
1016 public function moveFolderWithinStorage($sourceFolderIdentifier, $targetFolderIdentifier, $newFolderName)
1017 {
1018 $sourcePath = $this->getAbsolutePath($sourceFolderIdentifier);
1019 $relativeTargetPath = $this->canonicalizeAndCheckFolderIdentifier($targetFolderIdentifier . '/' . $newFolderName);
1020 $targetPath = $this->getAbsolutePath($relativeTargetPath);
1021 // get all files and folders we are going to move, to have a map for updating later.
1022 $filesAndFolders = $this->retrieveFileAndFoldersInPath($sourcePath, true);
1023 $result = rename($sourcePath, $targetPath);
1024 if ($result === false) {
1025 throw new \RuntimeException('Moving folder ' . $sourcePath . ' to ' . $targetPath . ' failed.', 1320711817);
1026 }
1027 // Create a mapping from old to new identifiers
1028 $identifierMap = $this->createIdentifierMap($filesAndFolders, $sourceFolderIdentifier, $relativeTargetPath);
1029 return $identifierMap;
1030 }
1031
1032 /**
1033 * Folder equivalent to copyFileWithinStorage().
1034 *
1035 * @param string $sourceFolderIdentifier
1036 * @param string $targetFolderIdentifier
1037 * @param string $newFolderName
1038 *
1039 * @return bool
1040 * @throws Exception\FileOperationErrorException
1041 */
1042 public function copyFolderWithinStorage($sourceFolderIdentifier, $targetFolderIdentifier, $newFolderName)
1043 {
1044 // This target folder path already includes the topmost level, i.e. the folder this method knows as $folderToCopy.
1045 // We can thus rely on this folder being present and just create the subfolder we want to copy to.
1046 $newFolderIdentifier = $this->canonicalizeAndCheckFolderIdentifier($targetFolderIdentifier . '/' . $newFolderName);
1047 $sourceFolderPath = $this->getAbsolutePath($sourceFolderIdentifier);
1048 $targetFolderPath = $this->getAbsolutePath($newFolderIdentifier);
1049
1050 mkdir($targetFolderPath);
1051 /** @var $iterator \RecursiveDirectoryIterator */
1052 $iterator = new \RecursiveIteratorIterator(
1053 new \RecursiveDirectoryIterator($sourceFolderPath),
1054 \RecursiveIteratorIterator::SELF_FIRST,
1055 \RecursiveIteratorIterator::CATCH_GET_CHILD
1056 );
1057 // Rewind the iterator as this is important for some systems e.g. Windows
1058 $iterator->rewind();
1059 while ($iterator->valid()) {
1060 /** @var $current \RecursiveDirectoryIterator */
1061 $current = $iterator->current();
1062 $fileName = $current->getFilename();
1063 $itemSubPath = GeneralUtility::fixWindowsFilePath($iterator->getSubPathname());
1064 if ($current->isDir() && !($fileName === '..' || $fileName === '.')) {
1065 GeneralUtility::mkdir($targetFolderPath . '/' . $itemSubPath);
1066 } elseif ($current->isFile()) {
1067 $copySourcePath = $sourceFolderPath . '/' . $itemSubPath;
1068 $copyTargetPath = $targetFolderPath . '/' . $itemSubPath;
1069 $result = copy($copySourcePath, $copyTargetPath);
1070 if ($result === false) {
1071 // rollback
1072 GeneralUtility::rmdir($targetFolderIdentifier, true);
1073 throw new Exception\FileOperationErrorException(
1074 'Copying resource "' . $copySourcePath . '" to "' . $copyTargetPath . '" failed.',
1075 1330119452
1076 );
1077 }
1078 }
1079 $iterator->next();
1080 }
1081 GeneralUtility::fixPermissions($targetFolderPath, true);
1082 return true;
1083 }
1084
1085 /**
1086 * Renames a file in this storage.
1087 *
1088 * @param string $fileIdentifier
1089 * @param string $newName The target path (including the file name!)
1090 * @return string The identifier of the file after renaming
1091 * @throws Exception\ExistingTargetFileNameException
1092 * @throws \RuntimeException
1093 */
1094 public function renameFile($fileIdentifier, $newName)
1095 {
1096 // Makes sure the Path given as parameter is valid
1097 $newName = $this->sanitizeFileName($newName);
1098 $newIdentifier = rtrim(GeneralUtility::fixWindowsFilePath(PathUtility::dirname($fileIdentifier)), '/') . '/' . $newName;
1099 $newIdentifier = $this->canonicalizeAndCheckFileIdentifier($newIdentifier);
1100 // The target should not exist already
1101 if ($this->fileExists($newIdentifier)) {
1102 throw new Exception\ExistingTargetFileNameException(
1103 'The target file "' . $newIdentifier . '" already exists.',
1104 1320291063
1105 );
1106 }
1107 $sourcePath = $this->getAbsolutePath($fileIdentifier);
1108 $targetPath = $this->getAbsolutePath($newIdentifier);
1109 $result = rename($sourcePath, $targetPath);
1110 if ($result === false) {
1111 throw new \RuntimeException('Renaming file ' . $sourcePath . ' to ' . $targetPath . ' failed.', 1320375115);
1112 }
1113 return $newIdentifier;
1114 }
1115
1116 /**
1117 * Renames a folder in this storage.
1118 *
1119 * @param string $folderIdentifier
1120 * @param string $newName
1121 * @return array A map of old to new file identifiers of all affected files and folders
1122 * @throws \RuntimeException if renaming the folder failed
1123 */
1124 public function renameFolder($folderIdentifier, $newName)
1125 {
1126 $folderIdentifier = $this->canonicalizeAndCheckFolderIdentifier($folderIdentifier);
1127 $newName = $this->sanitizeFileName($newName);
1128
1129 $newIdentifier = PathUtility::dirname($folderIdentifier) . '/' . $newName;
1130 $newIdentifier = $this->canonicalizeAndCheckFolderIdentifier($newIdentifier);
1131
1132 $sourcePath = $this->getAbsolutePath($folderIdentifier);
1133 $targetPath = $this->getAbsolutePath($newIdentifier);
1134 // get all files and folders we are going to move, to have a map for updating later.
1135 $filesAndFolders = $this->retrieveFileAndFoldersInPath($sourcePath, true);
1136 $result = rename($sourcePath, $targetPath);
1137 if ($result === false) {
1138 throw new \RuntimeException(sprintf('Renaming folder "%1$s" to "%2$s" failed."', $sourcePath, $targetPath), 1320375116);
1139 }
1140 try {
1141 // Create a mapping from old to new identifiers
1142 $identifierMap = $this->createIdentifierMap($filesAndFolders, $folderIdentifier, $newIdentifier);
1143 } catch (\Exception $e) {
1144 rename($targetPath, $sourcePath);
1145 throw new \RuntimeException(
1146 sprintf(
1147 'Creating filename mapping after renaming "%1$s" to "%2$s" failed. Reverted rename operation.\\n\\nOriginal error: %3$s"',
1148 $sourcePath,
1149 $targetPath,
1150 $e->getMessage()
1151 ),
1152 1334160746
1153 );
1154 }
1155 return $identifierMap;
1156 }
1157
1158 /**
1159 * Removes a file from the filesystem. This does not check if the file is
1160 * still used or if it is a bad idea to delete it for some other reason
1161 * this has to be taken care of in the upper layers (e.g. the Storage)!
1162 *
1163 * @param string $fileIdentifier
1164 * @return bool TRUE if deleting the file succeeded
1165 * @throws \RuntimeException
1166 */
1167 public function deleteFile($fileIdentifier)
1168 {
1169 $filePath = $this->getAbsolutePath($fileIdentifier);
1170 $recycleDirectory = $this->getRecycleDirectory($filePath);
1171 if (!empty($recycleDirectory)) {
1172 $result = $this->recycleFileOrFolder($filePath, $recycleDirectory);
1173 } else {
1174 $result = unlink($filePath);
1175 }
1176 if ($result === false) {
1177 throw new \RuntimeException('Deletion of file ' . $fileIdentifier . ' failed.', 1320855304);
1178 }
1179 return $result;
1180 }
1181
1182 /**
1183 * Removes a folder from this storage.
1184 *
1185 * @param string $folderIdentifier
1186 * @param bool $deleteRecursively
1187 * @return bool
1188 * @throws Exception\FileOperationErrorException
1189 * @throws Exception\InvalidPathException
1190 */
1191 public function deleteFolder($folderIdentifier, $deleteRecursively = false)
1192 {
1193 $folderPath = $this->getAbsolutePath($folderIdentifier);
1194 $recycleDirectory = $this->getRecycleDirectory($folderPath);
1195 if (!empty($recycleDirectory) && $folderPath !== $recycleDirectory) {
1196 $result = $this->recycleFileOrFolder($folderPath, $recycleDirectory);
1197 } else {
1198 $result = GeneralUtility::rmdir($folderPath, $deleteRecursively);
1199 }
1200 if ($result === false) {
1201 throw new Exception\FileOperationErrorException(
1202 'Deleting folder "' . $folderIdentifier . '" failed.',
1203 1330119451
1204 );
1205 }
1206 return $result;
1207 }
1208
1209 /**
1210 * Checks if a folder contains files and (if supported) other folders.
1211 *
1212 * @param string $folderIdentifier
1213 * @return bool TRUE if there are no files and folders within $folder
1214 */
1215 public function isFolderEmpty($folderIdentifier)
1216 {
1217 $path = $this->getAbsolutePath($folderIdentifier);
1218 $dirHandle = opendir($path);
1219 while ($entry = readdir($dirHandle)) {
1220 if ($entry !== '.' && $entry !== '..') {
1221 closedir($dirHandle);
1222 return false;
1223 }
1224 }
1225 closedir($dirHandle);
1226 return true;
1227 }
1228
1229 /**
1230 * Returns (a local copy of) a file for processing it. This makes a copy
1231 * first when in writable mode, so if you change the file, you have to update it yourself afterwards.
1232 *
1233 * @param string $fileIdentifier
1234 * @param bool $writable Set this to FALSE if you only need the file for read operations.
1235 * This might speed up things, e.g. by using a cached local version.
1236 * Never modify the file if you have set this flag!
1237 * @return string The path to the file on the local disk
1238 */
1239 public function getFileForLocalProcessing($fileIdentifier, $writable = true)
1240 {
1241 if ($writable === false) {
1242 return $this->getAbsolutePath($fileIdentifier);
1243 }
1244 return $this->copyFileToTemporaryPath($fileIdentifier);
1245 }
1246
1247 /**
1248 * Returns the permissions of a file/folder as an array (keys r, w) of boolean flags
1249 *
1250 * @param string $identifier
1251 * @return array
1252 * @throws Exception\ResourcePermissionsUnavailableException
1253 */
1254 public function getPermissions($identifier)
1255 {
1256 $path = $this->getAbsolutePath($identifier);
1257 $permissionBits = fileperms($path);
1258 if ($permissionBits === false) {
1259 throw new Exception\ResourcePermissionsUnavailableException('Error while fetching permissions for ' . $path, 1319455097);
1260 }
1261 return [
1262 'r' => (bool)is_readable($path),
1263 'w' => (bool)is_writable($path)
1264 ];
1265 }
1266
1267 /**
1268 * Checks if a given identifier is within a container, e.g. if
1269 * a file or folder is within another folder. It will also return
1270 * TRUE if both canonicalized identifiers are equal.
1271 *
1272 * @param string $folderIdentifier
1273 * @param string $identifier identifier to be checked against $folderIdentifier
1274 * @return bool TRUE if $content is within or matches $folderIdentifier
1275 */
1276 public function isWithin($folderIdentifier, $identifier)
1277 {
1278 $folderIdentifier = $this->canonicalizeAndCheckFileIdentifier($folderIdentifier);
1279 $entryIdentifier = $this->canonicalizeAndCheckFileIdentifier($identifier);
1280 if ($folderIdentifier === $entryIdentifier) {
1281 return true;
1282 }
1283 // File identifier canonicalization will not modify a single slash so
1284 // we must not append another slash in that case.
1285 if ($folderIdentifier !== '/') {
1286 $folderIdentifier .= '/';
1287 }
1288 return GeneralUtility::isFirstPartOfStr($entryIdentifier, $folderIdentifier);
1289 }
1290
1291 /**
1292 * Creates a new (empty) file and returns the identifier.
1293 *
1294 * @param string $fileName
1295 * @param string $parentFolderIdentifier
1296 * @return string
1297 * @throws Exception\InvalidFileNameException
1298 * @throws \RuntimeException
1299 */
1300 public function createFile($fileName, $parentFolderIdentifier)
1301 {
1302 if (!$this->isValidFilename($fileName)) {
1303 throw new Exception\InvalidFileNameException(
1304 'Invalid characters in fileName "' . $fileName . '"',
1305 1320572272
1306 );
1307 }
1308 $parentFolderIdentifier = $this->canonicalizeAndCheckFolderIdentifier($parentFolderIdentifier);
1309 $fileIdentifier = $this->canonicalizeAndCheckFileIdentifier(
1310 $parentFolderIdentifier . $this->sanitizeFileName(ltrim($fileName, '/'))
1311 );
1312 $absoluteFilePath = $this->getAbsolutePath($fileIdentifier);
1313 $result = touch($absoluteFilePath);
1314 GeneralUtility::fixPermissions($absoluteFilePath);
1315 clearstatcache();
1316 if ($result !== true) {
1317 throw new \RuntimeException('Creating file ' . $fileIdentifier . ' failed.', 1320569854);
1318 }
1319 return $fileIdentifier;
1320 }
1321
1322 /**
1323 * Returns the contents of a file. Beware that this requires to load the
1324 * complete file into memory and also may require fetching the file from an
1325 * external location. So this might be an expensive operation (both in terms of
1326 * processing resources and money) for large files.
1327 *
1328 * @param string $fileIdentifier
1329 * @return string The file contents
1330 */
1331 public function getFileContents($fileIdentifier)
1332 {
1333 $filePath = $this->getAbsolutePath($fileIdentifier);
1334 return file_get_contents($filePath);
1335 }
1336
1337 /**
1338 * Sets the contents of a file to the specified value.
1339 *
1340 * @param string $fileIdentifier
1341 * @param string $contents
1342 * @return int The number of bytes written to the file
1343 * @throws \RuntimeException if the operation failed
1344 */
1345 public function setFileContents($fileIdentifier, $contents)
1346 {
1347 $filePath = $this->getAbsolutePath($fileIdentifier);
1348 $result = file_put_contents($filePath, $contents);
1349
1350 // Make sure later calls to filesize() etc. return correct values.
1351 clearstatcache(true, $filePath);
1352
1353 if ($result === false) {
1354 throw new \RuntimeException('Setting contents of file "' . $fileIdentifier . '" failed.', 1325419305);
1355 }
1356 return $result;
1357 }
1358
1359 /**
1360 * Returns the role of an item (currently only folders; can later be extended for files as well)
1361 *
1362 * @param string $folderIdentifier
1363 * @return string
1364 */
1365 public function getRole($folderIdentifier)
1366 {
1367 $name = PathUtility::basename($folderIdentifier);
1368 $role = $this->mappingFolderNameToRole[$name];
1369 if (empty($role)) {
1370 $role = FolderInterface::ROLE_DEFAULT;
1371 }
1372 return $role;
1373 }
1374
1375 /**
1376 * Directly output the contents of the file to the output
1377 * buffer. Should not take care of header files or flushing
1378 * buffer before. Will be taken care of by the Storage.
1379 *
1380 * @param string $identifier
1381 */
1382 public function dumpFileContents($identifier)
1383 {
1384 readfile($this->getAbsolutePath($this->canonicalizeAndCheckFileIdentifier($identifier)), 0);
1385 }
1386
1387 /**
1388 * Get the path of the nearest recycler folder of a given $path.
1389 * Return an empty string if there is no recycler folder available.
1390 *
1391 * @param string $path
1392 * @return string
1393 */
1394 protected function getRecycleDirectory($path)
1395 {
1396 $recyclerSubdirectory = array_search(FolderInterface::ROLE_RECYCLER, $this->mappingFolderNameToRole, true);
1397 if ($recyclerSubdirectory === false) {
1398 return '';
1399 }
1400 $rootDirectory = rtrim($this->getAbsolutePath($this->getRootLevelFolder()), '/');
1401 $searchDirectory = PathUtility::dirname($path);
1402 // Check if file or folder to be deleted is inside a recycler directory
1403 if ($this->getRole($searchDirectory) === FolderInterface::ROLE_RECYCLER) {
1404 $searchDirectory = PathUtility::dirname($searchDirectory);
1405 // Check if file or folder to be deleted is inside the root recycler
1406 if ($searchDirectory == $rootDirectory) {
1407 return '';
1408 }
1409 $searchDirectory = PathUtility::dirname($searchDirectory);
1410 }
1411 // Search for the closest recycler directory
1412 while ($searchDirectory) {
1413 $recycleDirectory = $searchDirectory . '/' . $recyclerSubdirectory;
1414 if (is_dir($recycleDirectory)) {
1415 return $recycleDirectory;
1416 }
1417 if ($searchDirectory === $rootDirectory) {
1418 return '';
1419 }
1420 $searchDirectory = PathUtility::dirname($searchDirectory);
1421 }
1422
1423 return '';
1424 }
1425 }