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