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