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