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