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