[BUGFIX] Some unit tests fail in Core::LocalDriverTest
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Resource / Driver / LocalDriver.php
1 <?php
2 namespace TYPO3\CMS\Core\Resource\Driver;
3 use TYPO3\CMS\Core\Utility\GeneralUtility;
4
5 /***************************************************************
6 * Copyright notice
7 *
8 * (c) 2011 Andreas Wolf <andreas.wolf@ikt-werk.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 /**
32 * Driver for the local file system
33 *
34 * @author Andreas Wolf <andreas.wolf@ikt-werk.de>
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 } else {
262 // default for Backend
263 $charset = 'utf-8';
264 }
265 }
266 // If a charset was found, convert fileName
267 if ($charset) {
268 $fileName = $this->getCharsetConversion()->specCharsToASCII($charset, $fileName);
269 }
270 // Replace unwanted characters by underscores
271 $cleanFileName = preg_replace('/[^.[:alnum:]_-]/', '_', trim($fileName));
272 }
273 // Strip trailing dots and return
274 $cleanFileName = preg_replace('/\\.*$/', '', $cleanFileName);
275 if (!$cleanFileName) {
276 throw new \TYPO3\CMS\Core\Resource\Exception\InvalidFileNameException('File name ' . $cleanFileName . ' is invalid.', 1320288991);
277 }
278 return $cleanFileName;
279 }
280
281 /**
282 * Generic wrapper for extracting a list of items from a path. The
283 * extraction itself is done by the given handler method
284 *
285 * @param string $path
286 * @param integer $start The position to start the listing; if not set, start from the beginning
287 * @param integer $numberOfItems The number of items to list; if set to zero, all items are returned
288 * @param array $filterMethods The filter methods used to filter the directory items
289 * @param string $itemHandlerMethod The method (in this class) that handles the single iterator elements.
290 * @param array $itemRows
291 * @return array
292 */
293 // TODO add unit tests
294 protected function getDirectoryItemList($path, $start, $numberOfItems, array $filterMethods, $itemHandlerMethod, $itemRows = array()) {
295 $realPath = rtrim(($this->absoluteBasePath . trim($path, '/')), '/') . '/';
296 if (!is_dir($realPath)) {
297 throw new \InvalidArgumentException('Cannot list items in directory ' . $path . ' - does not exist or is no directory', 1314349666);
298 }
299 if ($start > 0) {
300 $start--;
301 }
302 // Fetch the files and folders and sort them by name; we have to do
303 // this here because the directory iterator does return them in
304 // an arbitrary order
305 $items = $this->getFileAndFoldernamesInPath($realPath);
306 natcasesort($items);
307 $iterator = new \ArrayIterator($items);
308 if ($iterator->count() == 0) {
309 return array();
310 }
311 $iterator->seek($start);
312 if ($path !== '' && $path !== '/') {
313 $path = '/' . trim($path, '/') . '/';
314 }
315 // $c is the counter for how many items we still have to fetch (-1 is unlimited)
316 $c = $numberOfItems > 0 ? $numberOfItems : -1;
317 $items = array();
318 while ($iterator->valid() && ($numberOfItems == 0 || $c > 0)) {
319 // $iteratorItem is the file or folder name
320 $iteratorItem = $iterator->current();
321 // go on to the next iterator item now as we might skip this one early
322 $iterator->next();
323 $identifier = $path . $iteratorItem;
324 if ($this->applyFilterMethodsToDirectoryItem($filterMethods, $iteratorItem, $identifier, $path) === FALSE) {
325 continue;
326 }
327 if (isset($itemRows[$identifier])) {
328 list($key, $item) = $this->{$itemHandlerMethod}($iteratorItem, $path, $itemRows[$identifier]);
329 } else {
330 list($key, $item) = $this->{$itemHandlerMethod}($iteratorItem, $path);
331 }
332 if (empty($item)) {
333 continue;
334 }
335 $items[$key] = $item;
336 // Decrement item counter to make sure we only return $numberOfItems
337 // we cannot do this earlier in the method (unlike moving the iterator forward) because we only add the
338 // item here
339 --$c;
340 }
341 return $items;
342 }
343
344 /**
345 * Handler for items in a file list.
346 *
347 * @param string $fileName
348 * @param string $path
349 * @param array $fileRow The pre-loaded file row
350 * @return array
351 */
352 protected function getFileList_itemCallback($fileName, $path, array $fileRow = array()) {
353 $filePath = $this->getAbsolutePath($path . $fileName);
354 if (!is_file($filePath)) {
355 return array('', array());
356 }
357 // TODO add unit test for existing file row case
358 if (!empty($fileRow) && filemtime($filePath) <= $fileRow['modification_date']) {
359 return array($fileName, $fileRow);
360 } else {
361 return array($fileName, $this->extractFileInformation($filePath, $path));
362 }
363 }
364
365 /**
366 * Handler for items in a directory listing.
367 *
368 * @param string $folderName The folder's name
369 * @param string $parentPath The path to the folder's parent folder
370 * @param array $folderRow [optional]
371 * @return array
372 */
373 protected function getFolderList_itemCallback($folderName, $parentPath, array $folderRow = array()) {
374 $folderPath = $this->getAbsolutePath($parentPath . $folderName);
375 if (!is_dir($folderPath)) {
376 return array('', array());
377 }
378 // also don't show hidden files
379 if ($folderName === '..' || $folderName === '.' || $folderName === '') {
380 return array('', array());
381 }
382 // remove the trailing slash from the folder name (the trailing slash comes from the DirectoryIterator)
383 $folderName = substr($folderName, 0, -1);
384 return array($folderName, $this->extractFolderInformation($folderPath, $parentPath));
385 }
386
387 /**
388 * Returns a list with the names of all files and folders in a path, optionally recursive.
389 * Folder names have a trailing slash.
390 *
391 * @param string $path The absolute path
392 * @param bool $recursive If TRUE, recursively fetches files and folders
393 * @return array
394 */
395 protected function getFileAndFoldernamesInPath($path, $recursive = FALSE) {
396 if ($recursive) {
397 $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, \FilesystemIterator::CURRENT_AS_FILEINFO));
398 } else {
399 $iterator = new \RecursiveDirectoryIterator($path, \FilesystemIterator::CURRENT_AS_FILEINFO);
400 }
401 $directoryEntries = array();
402 while ($iterator->valid()) {
403 /** @var $entry \SplFileInfo */
404 $entry = $iterator->current();
405 // skip non-files/non-folders, and empty entries
406 if (!$entry->isFile() && !$entry->isDir() || $entry->getFilename() == '') {
407 $iterator->next();
408 continue;
409 }
410 // skip the pseudo-directories "." and ".."
411 if ($entry->getFilename() == '..' || $entry->getFilename() == '.') {
412 $iterator->next();
413 continue;
414 }
415 $entryPath = GeneralUtility::fixWindowsFilePath(substr($entry->getPathname(), strlen($path)));
416 if ($entry->isDir()) {
417 $entryPath .= '/';
418 }
419 $directoryEntries[] = $entryPath;
420 $iterator->next();
421 }
422 return $directoryEntries;
423 }
424
425 /**
426 * Extracts information about a file from the filesystem.
427 *
428 * @param string $filePath The absolute path to the file
429 * @param string $containerPath The relative path to the file's container
430 * @return array
431 */
432 protected function extractFileInformation($filePath, $containerPath) {
433 $fileName = basename($filePath);
434 $fileInformation = array(
435 'size' => filesize($filePath),
436 'atime' => fileatime($filePath),
437 'mtime' => filemtime($filePath),
438 'ctime' => filectime($filePath),
439 'mimetype' => $this->getMimeTypeOfFile($filePath),
440 'name' => $fileName,
441 'identifier' => $containerPath . $fileName,
442 'storage' => $this->storage->getUid()
443 );
444 return $fileInformation;
445 }
446
447 /**
448 * Extracts information about a folder from the filesystem.
449 *
450 * @param string $folderPath The absolute path to the folder
451 * @param string $containerPath The relative path to the folder's container inside the storage (must end with a trailing slash)
452 * @return array
453 */
454 protected function extractFolderInformation($folderPath, $containerPath) {
455 $folderName = basename($folderPath);
456 $folderInformation = array(
457 'ctime' => filectime($folderPath),
458 'mtime' => filemtime($folderPath),
459 'name' => $folderName,
460 'identifier' => $containerPath . $folderName . '/',
461 'storage' => $this->storage->getUid()
462 );
463 return $folderInformation;
464 }
465
466 /**
467 * Returns the absolute path of the folder this driver operates on.
468 *
469 * @return string
470 */
471 public function getAbsoluteBasePath() {
472 return $this->absoluteBasePath;
473 }
474
475 /**
476 * Returns the absolute path of a file or folder.
477 *
478 * @param \TYPO3\CMS\Core\Resource\FileInterface|\TYPO3\CMS\Core\Resource\Folder|string $file
479 * @return string
480 */
481 public function getAbsolutePath($file) {
482 if ($file instanceof \TYPO3\CMS\Core\Resource\FileInterface) {
483 $path = $this->absoluteBasePath . ltrim($file->getIdentifier(), '/');
484 } elseif ($file instanceof \TYPO3\CMS\Core\Resource\Folder) {
485 // We can assume a trailing slash here because it is added by the folder object on construction.
486 $path = $this->absoluteBasePath . ltrim($file->getIdentifier(), '/');
487 } elseif (is_string($file)) {
488 $path = $this->absoluteBasePath . ltrim($file, '/');
489 } else {
490 throw new \RuntimeException('Type "' . gettype($file) . '" is not supported.', 1325191178);
491 }
492 return $path;
493 }
494
495 /**
496 * Returns metadata of a file (size, times, mimetype)
497 *
498 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
499 * @return array
500 */
501 public function getLowLevelFileInfo(\TYPO3\CMS\Core\Resource\FileInterface $file) {
502 // TODO define which data should be returned
503 // TODO write unit test
504 // TODO cache this info. Registry?
505 // TODO merge with extractFolderInformation() above?!
506 $filePath = $this->getAbsolutePath($file);
507 $fileStat = stat($filePath);
508 $mimeType = $this->getMimeTypeOfFile($filePath);
509 $stat = array(
510 'size' => filesize($filePath),
511 'atime' => $fileStat['atime'],
512 'mtime' => $fileStat['mtime'],
513 'ctime' => $fileStat['ctime'],
514 'nlink' => $fileStat['nlink'],
515 'type' => $mimeType,
516 'mimetype' => $mimeType
517 );
518 return $stat;
519 }
520
521 /**
522 * Get mime type of file.
523 *
524 * @param string $absoluteFilePath Absolute path to file
525 * @return string Mime type. eg, text/html
526 */
527 protected function getMimeTypeOfFile($absoluteFilePath) {
528 $fileInfo = new \finfo();
529 return $fileInfo->file($absoluteFilePath, FILEINFO_MIME_TYPE);
530 }
531
532 /**
533 * Creates a (cryptographic) hash for a file.
534 *
535 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
536 * @param string $hashAlgorithm The hash algorithm to use
537 * @return string
538 */
539 public function hash(\TYPO3\CMS\Core\Resource\FileInterface $file, $hashAlgorithm) {
540 if (!in_array($hashAlgorithm, $this->getSupportedHashAlgorithms())) {
541 throw new \InvalidArgumentException('Hash algorithm "' . $hashAlgorithm . '" is not supported.', 1304964032);
542 }
543 switch ($hashAlgorithm) {
544 case 'sha1':
545 $hash = sha1_file($this->getAbsolutePath($file));
546 break;
547 case 'md5':
548 $hash = md5_file($this->getAbsolutePath($file));
549 break;
550 default:
551 throw new \RuntimeException('Hash algorithm ' . $hashAlgorithm . ' is not implemented.', 1329644451);
552 }
553 return $hash;
554 }
555
556 /**
557 * Adds a file from the local server hard disk to a given path in TYPO3s virtual file system.
558 *
559 * This assumes that the local file exists, so no further check is done here!
560 *
561 * @param string $localFilePath
562 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder
563 * @param string $fileName The name to add the file under
564 * @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.
565 * @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
566 * @return \TYPO3\CMS\Core\Resource\FileInterface
567 */
568 public function addFile($localFilePath, \TYPO3\CMS\Core\Resource\Folder $targetFolder, $fileName, \TYPO3\CMS\Core\Resource\AbstractFile $updateFileObject = NULL) {
569 // as for the "virtual storage" for backwards-compatibility, this check always fails, as the file probably lies under PATH_site
570 // thus, it is not checked here
571 if (\TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($localFilePath, $this->absoluteBasePath) && $this->storage->getUid() > 0) {
572 throw new \InvalidArgumentException('Cannot add a file that is already part of this storage.', 1314778269);
573 }
574 $relativeTargetPath = ltrim($targetFolder->getIdentifier(), '/');
575 $relativeTargetPath .= $fileName ? $fileName : basename($localFilePath);
576 $targetPath = $this->absoluteBasePath . $relativeTargetPath;
577 if (is_uploaded_file($localFilePath)) {
578 $moveResult = move_uploaded_file($localFilePath, $targetPath);
579 } else {
580 $moveResult = rename($localFilePath, $targetPath);
581 }
582 if ($moveResult !== TRUE) {
583 throw new \RuntimeException('Moving file ' . $localFilePath . ' to ' . $targetPath . ' failed.', 1314803096);
584 }
585 clearstatcache();
586 // Change the permissions of the file
587 \TYPO3\CMS\Core\Utility\GeneralUtility::fixPermissions($targetPath);
588 $fileInfo = $this->getFileInfoByIdentifier($relativeTargetPath);
589 if ($updateFileObject) {
590 $updateFileObject->updateProperties($fileInfo);
591 return $updateFileObject;
592 } else {
593 $fileObject = $this->getFileObject($fileInfo);
594 return $fileObject;
595 }
596 }
597
598 /**
599 * Checks if a resource exists - does not care for the type (file or folder).
600 *
601 * @param $identifier
602 * @return boolean
603 */
604 public function resourceExists($identifier) {
605 $absoluteResourcePath = $this->absoluteBasePath . ltrim($identifier, '/');
606 return file_exists($absoluteResourcePath);
607 }
608
609 /**
610 * Checks if a file exists.
611 *
612 * @param string $identifier
613 * @return boolean
614 */
615 public function fileExists($identifier) {
616 $absoluteFilePath = $this->absoluteBasePath . ltrim($identifier, '/');
617 return is_file($absoluteFilePath);
618 }
619
620 /**
621 * Checks if a file inside a storage folder exists
622 *
623 * @param string $fileName
624 * @param \TYPO3\CMS\Core\Resource\Folder $folder
625 * @return boolean
626 */
627 public function fileExistsInFolder($fileName, \TYPO3\CMS\Core\Resource\Folder $folder) {
628 $identifier = ltrim($folder->getIdentifier(), '/') . $fileName;
629 return $this->fileExists($identifier);
630 }
631
632 /**
633 * Checks if a folder exists.
634 *
635 * @param string $identifier
636 * @return boolean
637 */
638 public function folderExists($identifier) {
639 $absoluteFilePath = $this->absoluteBasePath . ltrim($identifier, '/');
640 return is_dir($absoluteFilePath);
641 }
642
643 /**
644 * Checks if a file inside a storage folder exists.
645 *
646 * @param string $folderName
647 * @param \TYPO3\CMS\Core\Resource\Folder $folder
648 * @return boolean
649 */
650 public function folderExistsInFolder($folderName, \TYPO3\CMS\Core\Resource\Folder $folder) {
651 $identifier = $folder->getIdentifier() . $folderName;
652 return $this->folderExists($identifier);
653 }
654
655 /**
656 * Returns a folder within the given folder.
657 *
658 * @param string $name The name of the folder to get
659 * @param \TYPO3\CMS\Core\Resource\Folder $parentFolder
660 * @return \TYPO3\CMS\Core\Resource\Folder
661 */
662 public function getFolderInFolder($name, \TYPO3\CMS\Core\Resource\Folder $parentFolder) {
663 $folderIdentifier = $parentFolder->getIdentifier() . $name . '/';
664 return $this->getFolder($folderIdentifier);
665 }
666
667 /**
668 * Replaces the contents (and file-specific metadata) of a file object with a local file.
669 *
670 * @param \TYPO3\CMS\Core\Resource\AbstractFile $file
671 * @param string $localFilePath
672 * @return boolean TRUE if the operation succeeded
673 */
674 public function replaceFile(\TYPO3\CMS\Core\Resource\AbstractFile $file, $localFilePath) {
675 $filePath = $this->getAbsolutePath($file);
676 $result = rename($localFilePath, $filePath);
677 if ($result === FALSE) {
678 throw new \RuntimeException('Replacing file ' . $filePath . ' with ' . $localFilePath . ' failed.', 1315314711);
679 }
680 $fileInfo = $this->getFileInfoByIdentifier($file->getIdentifier());
681 $file->updateProperties($fileInfo);
682 // TODO update index
683 return $result;
684 }
685
686 /**
687 * Adds a file at the specified location. This should only be used internally.
688 *
689 * @param string $localFilePath
690 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder
691 * @param string $targetFileName
692 * @return boolean TRUE if adding the file succeeded
693 */
694 public function addFileRaw($localFilePath, \TYPO3\CMS\Core\Resource\Folder $targetFolder, $targetFileName) {
695 $fileIdentifier = $targetFolder->getIdentifier() . $targetFileName;
696 $absoluteFilePath = $this->absoluteBasePath . $fileIdentifier;
697 $result = copy($localFilePath, $absoluteFilePath);
698 if ($result === FALSE || !file_exists($absoluteFilePath)) {
699 throw new \RuntimeException('Adding file ' . $localFilePath . ' at ' . $fileIdentifier . ' failed.');
700 }
701 return $fileIdentifier;
702 }
703
704 /**
705 * Deletes a file without access and usage checks. This should only be used internally.
706 *
707 * This accepts an identifier instead of an object because we might want to delete files that have no object
708 * associated with (or we don't want to create an object for) them - e.g. when moving a file to another storage.
709 *
710 * @param string $identifier
711 * @return bool TRUE if removing the file succeeded
712 */
713 public function deleteFileRaw($identifier) {
714 $targetPath = $this->absoluteBasePath . ltrim($identifier, '/');
715 $result = unlink($targetPath);
716 if ($result === FALSE || file_exists($targetPath)) {
717 throw new \RuntimeException('Deleting file ' . $identifier . ' failed.', 1320381534);
718 }
719 return TRUE;
720 }
721
722 /**
723 * Copies a file *within* the current storage.
724 * Note that this is only about an intra-storage move action, where a file is just
725 * moved to another folder in the same storage.
726 *
727 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
728 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder
729 * @param string $fileName
730 * @return \TYPO3\CMS\Core\Resource\FileInterface The new (copied) file object.
731 */
732 public function copyFileWithinStorage(\TYPO3\CMS\Core\Resource\FileInterface $file, \TYPO3\CMS\Core\Resource\Folder $targetFolder, $fileName) {
733 // TODO add unit test
734 $sourcePath = $this->getAbsolutePath($file);
735 $targetPath = ltrim($targetFolder->getIdentifier(), '/') . $fileName;
736 copy($sourcePath, $this->absoluteBasePath . $targetPath);
737 return $this->getFile($targetPath);
738 }
739
740 /**
741 * Moves a file *within* the current storage.
742 * Note that this is only about an intra-storage move action, where a file is just
743 * moved to another folder in the same storage.
744 *
745 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
746 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder
747 * @param string $fileName
748 * @return boolean
749 */
750 public function moveFileWithinStorage(\TYPO3\CMS\Core\Resource\FileInterface $file, \TYPO3\CMS\Core\Resource\Folder $targetFolder, $fileName) {
751 $sourcePath = $this->getAbsolutePath($file);
752 $targetIdentifier = $targetFolder->getIdentifier() . $fileName;
753 $result = rename($sourcePath, $this->absoluteBasePath . $targetIdentifier);
754 if ($result === FALSE) {
755 throw new \RuntimeException('Moving file ' . $sourcePath . ' to ' . $targetIdentifier . ' failed.', 1315314712);
756 }
757 return $targetIdentifier;
758 }
759
760 /**
761 * Copies a file to a temporary path and returns that path.
762 *
763 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
764 * @return string The temporary path
765 */
766 public function copyFileToTemporaryPath(\TYPO3\CMS\Core\Resource\FileInterface $file) {
767 $sourcePath = $this->getAbsolutePath($file);
768 $temporaryPath = $this->getTemporaryPathForFile($file);
769 $result = copy($sourcePath, $temporaryPath);
770 if ($result === FALSE) {
771 throw new \RuntimeException('Copying file ' . $file->getIdentifier() . ' to temporary path failed.', 1320577649);
772 }
773 return $temporaryPath;
774 }
775
776 /**
777 * Creates a map of old and new file/folder identifiers after renaming or
778 * moving a folder. The old identifier is used as the key, the new one as the value.
779 *
780 * @param array $filesAndFolders
781 * @param string $relativeSourcePath
782 * @param string $relativeTargetPath
783 * @return array
784 */
785 protected function createIdentifierMap(array $filesAndFolders, $relativeSourcePath, $relativeTargetPath) {
786 $identifierMap = array();
787 $identifierMap[$relativeSourcePath] = $relativeTargetPath;
788 foreach ($filesAndFolders as $oldSubIdentifier) {
789 $oldIdentifier = $relativeSourcePath . $oldSubIdentifier;
790 $newIdentifier = $relativeTargetPath . $oldSubIdentifier;
791 if (!$this->resourceExists($newIdentifier)) {
792 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);
793 }
794 $identifierMap[$oldIdentifier] = $newIdentifier;
795 }
796 return $identifierMap;
797 }
798
799 /**
800 * Folder equivalent to moveFileWithinStorage().
801 *
802 * @param \TYPO3\CMS\Core\Resource\Folder $folderToMove
803 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder
804 * @param string $newFolderName
805 * @return array A map of old to new file identifiers
806 */
807 public function moveFolderWithinStorage(\TYPO3\CMS\Core\Resource\Folder $folderToMove, \TYPO3\CMS\Core\Resource\Folder $targetFolder, $newFolderName) {
808 $relativeSourcePath = $folderToMove->getIdentifier();
809 $sourcePath = $this->getAbsolutePath($relativeSourcePath);
810 $relativeTargetPath = $targetFolder->getIdentifier() . $newFolderName . '/';
811 $targetPath = $this->getAbsolutePath($relativeTargetPath);
812 // get all files and folders we are going to move, to have a map for updating later.
813 $filesAndFolders = $this->getFileAndFoldernamesInPath($sourcePath, TRUE);
814 $result = rename($sourcePath, $targetPath);
815 if ($result === FALSE) {
816 throw new \RuntimeException('Moving folder ' . $sourcePath . ' to ' . $targetPath . ' failed.', 1320711817);
817 }
818 // Create a mapping from old to new identifiers
819 $identifierMap = $this->createIdentifierMap($filesAndFolders, $relativeSourcePath, $relativeTargetPath);
820 return $identifierMap;
821 }
822
823 /**
824 * Folder equivalent to copyFileWithinStorage().
825 *
826 * @param \TYPO3\CMS\Core\Resource\Folder $folderToCopy
827 * @param \TYPO3\CMS\Core\Resource\Folder $targetFolder
828 * @param string $newFolderName
829 * @return boolean
830 */
831 public function copyFolderWithinStorage(\TYPO3\CMS\Core\Resource\Folder $folderToCopy, \TYPO3\CMS\Core\Resource\Folder $targetFolder, $newFolderName) {
832 // This target folder path already includes the topmost level, i.e. the folder this method knows as $folderToCopy.
833 // We can thus rely on this folder being present and just create the subfolder we want to copy to.
834 $targetFolderPath = $this->getAbsolutePath($targetFolder) . $newFolderName . '/';
835 mkdir($targetFolderPath);
836 $sourceFolderPath = $this->getAbsolutePath($folderToCopy);
837 /** @var $iterator RecursiveDirectoryIterator */
838 $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($sourceFolderPath));
839 while ($iterator->valid()) {
840 /** @var $current RecursiveDirectoryIterator */
841 $current = $iterator->current();
842 $itemSubPath = $iterator->getSubPathname();
843 if ($current->isDir() && !($itemSubPath === '..' || $itemSubPath === '.')) {
844 mkdir($targetFolderPath . $itemSubPath);
845 } elseif ($current->isFile()) {
846 $result = copy($sourceFolderPath . $itemSubPath, $targetFolderPath . $itemSubPath);
847 if ($result === FALSE) {
848 throw new \TYPO3\CMS\Core\Resource\Exception\FileOperationErrorException('Copying file "' . $sourceFolderPath . $itemSubPath . '" to "' . $targetFolderPath . $itemSubPath . '" failed.', 1330119452);
849 }
850 }
851 $iterator->next();
852 }
853 return TRUE;
854 }
855
856 /**
857 * Renames a file in this storage.
858 *
859 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
860 * @param string $newName The target path (including the file name!)
861 * @return string The identifier of the file after renaming
862 */
863 public function renameFile(\TYPO3\CMS\Core\Resource\FileInterface $file, $newName) {
864 // Makes sure the Path given as parameter is valid
865 $newName = $this->sanitizeFileName($newName);
866 $newIdentifier = rtrim(GeneralUtility::fixWindowsFilePath(dirname($file->getIdentifier())), '/') . '/' . $newName;
867 // The target should not exist already
868 if ($this->fileExists($newIdentifier)) {
869 throw new \TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException('The target file already exists.', 1320291063);
870 }
871 $sourcePath = $this->getAbsolutePath($file);
872 $targetPath = $this->absoluteBasePath . '/' . ltrim($newIdentifier, '/');
873 $result = rename($sourcePath, $targetPath);
874 if ($result === FALSE) {
875 throw new \RuntimeException('Renaming file ' . $sourcePath . ' to ' . $targetPath . ' failed.', 1320375115);
876 }
877 return $newIdentifier;
878 }
879
880 /**
881 * Makes sure the Path given as parameter is valid
882 *
883 * @param string $filePath The file path (including the file name!)
884 * @return void
885 */
886 protected function checkFilePath($filePath) {
887 // filePath must be valid
888 if (!$this->isPathValid($filePath)) {
889 throw new \TYPO3\CMS\Core\Resource\Exception\InvalidPathException('File ' . $filePath . ' is not valid (".." and "//" is not allowed in path).', 1320286857);
890 }
891 }
892
893 /**
894 * Renames a folder in this storage.
895 *
896 * @param \TYPO3\CMS\Core\Resource\Folder $folder
897 * @param string $newName The target path (including the file name!)
898 * @return array A map of old to new file identifiers
899 * @throws \RuntimeException if renaming the folder failed
900 */
901 public function renameFolder(\TYPO3\CMS\Core\Resource\Folder $folder, $newName) {
902 // Makes sure the path given as parameter is valid
903 $newName = $this->sanitizeFileName($newName);
904 $relativeSourcePath = $folder->getIdentifier();
905 $sourcePath = $this->getAbsolutePath($relativeSourcePath);
906 $relativeTargetPath = rtrim(GeneralUtility::fixWindowsFilePath(dirname($relativeSourcePath)), '/') . '/' . $newName . '/';
907 $targetPath = $this->getAbsolutePath($relativeTargetPath);
908 // get all files and folders we are going to move, to have a map for updating later.
909 $filesAndFolders = $this->getFileAndFoldernamesInPath($sourcePath, TRUE);
910 $result = rename($sourcePath, $targetPath);
911 if ($result === FALSE) {
912 throw new \RuntimeException(sprintf('Renaming folder "%1$s" to "%2$s" failed."', $sourcePath, $targetPath), 1320375116);
913 }
914 try {
915 // Create a mapping from old to new identifiers
916 $identifierMap = $this->createIdentifierMap($filesAndFolders, $relativeSourcePath, $relativeTargetPath);
917 } catch (\Exception $e) {
918 rename($targetPath, $sourcePath);
919 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);
920 }
921 return $identifierMap;
922 }
923
924 /**
925 * Removes a file from this storage.
926 *
927 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
928 * @return boolean TRUE if deleting the file succeeded
929 */
930 public function deleteFile(\TYPO3\CMS\Core\Resource\FileInterface $file) {
931 $filePath = $this->getAbsolutePath($file);
932 $result = unlink($filePath);
933 if ($result === FALSE) {
934 throw new \RuntimeException('Deletion of file ' . $file->getIdentifier() . ' failed.', 1320855304);
935 }
936 return $result;
937 }
938
939 /**
940 * Removes a folder from this storage.
941 *
942 * @param \TYPO3\CMS\Core\Resource\Folder $folder
943 * @param bool $deleteRecursively
944 * @return boolean
945 */
946 public function deleteFolder(\TYPO3\CMS\Core\Resource\Folder $folder, $deleteRecursively = FALSE) {
947 $folderPath = $this->getAbsolutePath($folder);
948 $result = \TYPO3\CMS\Core\Utility\GeneralUtility::rmdir($folderPath, $deleteRecursively);
949 if ($result === FALSE) {
950 throw new \TYPO3\CMS\Core\Resource\Exception\FileOperationErrorException('Deleting folder "' . $folder->getIdentifier() . '" failed.', 1330119451);
951 }
952 return $result;
953 }
954
955 /**
956 * Checks if a folder contains files and (if supported) other folders.
957 *
958 * @param \TYPO3\CMS\Core\Resource\Folder $folder
959 * @return boolean TRUE if there are no files and folders within $folder
960 */
961 public function isFolderEmpty(\TYPO3\CMS\Core\Resource\Folder $folder) {
962 $path = $this->getAbsolutePath($folder);
963 $dirHandle = opendir($path);
964 while ($entry = readdir($dirHandle)) {
965 if ($entry !== '.' && $entry !== '..') {
966 closedir($dirHandle);
967 return FALSE;
968 }
969 }
970 return TRUE;
971 }
972
973 /**
974 * Returns a (local copy of) a file for processing it. This makes a copy
975 * first when in writable mode, so if you change the file,
976 * you have to update it yourself afterwards.
977 *
978 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
979 * @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!
980 * @return string The path to the file on the local disk
981 */
982 public function getFileForLocalProcessing(\TYPO3\CMS\Core\Resource\FileInterface $file, $writable = TRUE) {
983 if ($writable === FALSE) {
984 // TODO check if this is ok or introduce additional measures against file changes
985 return $this->getAbsolutePath($file);
986 } else {
987 // TODO check if this might also serve as a dump basic implementation in the abstract driver.
988 return $this->copyFileToTemporaryPath($file);
989 }
990 }
991
992 /**
993 * Returns the permissions of a file as an array (keys r, w) of boolean flags
994 *
995 * @param \TYPO3\CMS\Core\Resource\FileInterface $file The file object to check
996 * @return array
997 * @throws \RuntimeException If fetching the permissions failed
998 */
999 public function getFilePermissions(\TYPO3\CMS\Core\Resource\FileInterface $file) {
1000 $filePath = $this->getAbsolutePath($file);
1001 return $this->getPermissions($filePath);
1002 }
1003
1004 /**
1005 * Returns the permissions of a folder as an array (keys r, w) of boolean flags
1006 *
1007 * @param \TYPO3\CMS\Core\Resource\Folder $folder
1008 * @return array
1009 * @throws \RuntimeException If fetching the permissions failed
1010 */
1011 public function getFolderPermissions(\TYPO3\CMS\Core\Resource\Folder $folder) {
1012 $folderPath = $this->getAbsolutePath($folder);
1013 return $this->getPermissions($folderPath);
1014 }
1015
1016 /**
1017 * Helper function to unify access to permission information
1018 *
1019 * @param string $path
1020 * @return array
1021 * @throws \RuntimeException If fetching the permissions failed
1022 */
1023 protected function getPermissions($path) {
1024 $permissionBits = fileperms($path);
1025 if ($permissionBits === FALSE) {
1026 throw new \RuntimeException('Error while fetching permissions for ' . $path, 1319455097);
1027 }
1028 return array(
1029 'r' => (bool) is_readable($path),
1030 'w' => (bool) is_writable($path)
1031 );
1032 }
1033
1034 /**
1035 * Checks if a given object or identifier is within a container, e.g. if
1036 * a file or folder is within another folder.
1037 * This can e.g. be used to check for webmounts.
1038 *
1039 * @param \TYPO3\CMS\Core\Resource\Folder $container
1040 * @param mixed $content An object or an identifier to check
1041 * @return bool TRUE if $content is within $container, always FALSE if $container is not within this storage
1042 */
1043 public function isWithin(\TYPO3\CMS\Core\Resource\Folder $container, $content) {
1044 if ($container->getStorage() != $this->storage) {
1045 return FALSE;
1046 }
1047 if ($content instanceof \TYPO3\CMS\Core\Resource\FileInterface || $content instanceof \TYPO3\CMS\Core\Resource\Folder) {
1048 $content = $container->getIdentifier();
1049 }
1050 $folderPath = $container->getIdentifier();
1051 $content = '/' . ltrim($content, '/');
1052 return \TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($content, $folderPath);
1053 }
1054
1055 /**
1056 * Creates a new file and returns the matching file object for it.
1057 *
1058 * @param string $fileName
1059 * @param \TYPO3\CMS\Core\Resource\Folder $parentFolder
1060 * @return \TYPO3\CMS\Core\Resource\File
1061 */
1062 public function createFile($fileName, \TYPO3\CMS\Core\Resource\Folder $parentFolder) {
1063 if (!$this->isValidFilename($fileName)) {
1064 throw new \TYPO3\CMS\Core\Resource\Exception\InvalidFileNameException('Invalid characters in fileName "' . $fileName . '"', 1320572272);
1065 }
1066 $filePath = $parentFolder->getIdentifier() . ltrim($fileName, '/');
1067 // TODO set permissions of new file
1068 $result = touch($this->absoluteBasePath . $filePath);
1069 clearstatcache();
1070 if ($result !== TRUE) {
1071 throw new \RuntimeException('Creating file ' . $filePath . ' failed.', 1320569854);
1072 }
1073 $fileInfo = $this->getFileInfoByIdentifier($filePath);
1074 return $this->getFileObject($fileInfo);
1075 }
1076
1077 /**
1078 * Returns the contents of a file. Beware that this requires to load the
1079 * complete file into memory and also may require fetching the file from an
1080 * external location. So this might be an expensive operation (both in terms of
1081 * processing resources and money) for large files.
1082 *
1083 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
1084 * @return string The file contents
1085 */
1086 public function getFileContents(\TYPO3\CMS\Core\Resource\FileInterface $file) {
1087 $filePath = $this->getAbsolutePath($file);
1088 return file_get_contents($filePath);
1089 }
1090
1091 /**
1092 * Sets the contents of a file to the specified value.
1093 *
1094 * @param \TYPO3\CMS\Core\Resource\FileInterface $file
1095 * @param string $contents
1096 * @return integer The number of bytes written to the file
1097 * @throws \RuntimeException if the operation failed
1098 */
1099 public function setFileContents(\TYPO3\CMS\Core\Resource\FileInterface $file, $contents) {
1100 $filePath = $this->getAbsolutePath($file);
1101 $result = file_put_contents($filePath, $contents);
1102 if ($result === FALSE) {
1103 throw new \RuntimeException('Setting contents of file "' . $file->getIdentifier() . '" failed.', 1325419305);
1104 }
1105 return $result;
1106 }
1107
1108 /**
1109 * Gets the charset conversion object.
1110 *
1111 * @return \TYPO3\CMS\Core\Charset\CharsetConverter
1112 */
1113 protected function getCharsetConversion() {
1114 if (!isset($this->charsetConversion)) {
1115 if (TYPO3_MODE === 'FE') {
1116 $this->charsetConversion = $GLOBALS['TSFE']->csConvObj;
1117 } elseif (is_object($GLOBALS['LANG'])) {
1118 // BE assumed:
1119 $this->charsetConversion = $GLOBALS['LANG']->csConvObj;
1120 } else {
1121 // The object may not exist yet, so we need to create it now. Happens in the Install Tool for example.
1122 $this->charsetConversion = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Charset\\CharsetConverter');
1123 }
1124 }
1125 return $this->charsetConversion;
1126 }
1127
1128 }
1129
1130
1131 ?>