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