TYPO3 CMS  TYPO3_7-6
ResourceFactory.php
Go to the documentation of this file.
1 <?php
3 
4 /*
5  * This file is part of the TYPO3 CMS project.
6  *
7  * It is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU General Public License, either version 2
9  * of the License, or any later version.
10  *
11  * For the full copyright and license information, please read the
12  * LICENSE.txt file that was distributed with this source code.
13  *
14  * The TYPO3 project - inspiring people to share!
15  */
16 
22 
23 // @todo implement constructor-level caching
28 {
34  public static function getInstance()
35  {
36  return GeneralUtility::makeInstance(__CLASS__);
37  }
38 
42  protected $storageInstances = [];
43 
47  protected $collectionInstances = [];
48 
52  protected $fileInstances = [];
53 
57  protected $fileReferenceInstances = [];
58 
64  protected $localDriverStorageCache = null;
65 
70 
74  public function __construct(\TYPO3\CMS\Extbase\SignalSlot\Dispatcher $signalSlotDispatcher = null)
75  {
76  $this->signalSlotDispatcher = $signalSlotDispatcher ?: GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\SignalSlot\Dispatcher::class);
77  }
78 
87  public function getDriverObject($driverIdentificationString, array $driverConfiguration)
88  {
90  $driverRegistry = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\Driver\DriverRegistry::class);
91  $driverClass = $driverRegistry->getDriverClass($driverIdentificationString);
92  $driverObject = GeneralUtility::makeInstance($driverClass, $driverConfiguration);
93  return $driverObject;
94  }
95 
106  public function getDefaultStorage()
107  {
109  $storageRepository = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class);
110 
111  $allStorages = $storageRepository->findAll();
112  foreach ($allStorages as $storage) {
113  if ($storage->isDefault()) {
114  return $storage;
115  }
116  }
117  return null;
118  }
130  public function getStorageObject($uid, array $recordData = [], &$fileIdentifier = null)
131  {
132  if (!is_numeric($uid)) {
133  throw new \InvalidArgumentException('The UID of storage has to be numeric. UID given: "' . $uid . '"', 1314085991);
134  }
135  $uid = (int)$uid;
136  if ($uid === 0 && $fileIdentifier !== null) {
137  $uid = $this->findBestMatchingStorageByLocalPath($fileIdentifier);
138  }
139  if (!$this->storageInstances[$uid]) {
140  $storageConfiguration = null;
141  $storageObject = null;
142  // If the built-in storage with UID=0 is requested:
143  if ($uid === 0) {
144  $recordData = [
145  'uid' => 0,
146  'pid' => 0,
147  'name' => 'Fallback Storage',
148  'description' => 'Internal storage, mounting the main TYPO3_site directory.',
149  'driver' => 'Local',
150  'processingfolder' => 'typo3temp/_processed_/',
151  // legacy code
152  'configuration' => '',
153  'is_online' => true,
154  'is_browsable' => true,
155  'is_public' => true,
156  'is_writable' => true,
157  'is_default' => false,
158  ];
159  $storageConfiguration = [
160  'basePath' => '/',
161  'pathType' => 'relative'
162  ];
163  } elseif (count($recordData) === 0 || (int)$recordData['uid'] !== $uid) {
165  $storageRepository = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class);
167  $storageObject = $storageRepository->findByUid($uid);
168  }
169  if (!$storageObject instanceof ResourceStorage) {
170  $storageObject = $this->createStorageObject($recordData, $storageConfiguration);
171  }
172  $this->emitPostProcessStorageSignal($storageObject);
173  $this->storageInstances[$uid] = $storageObject;
174  }
175  return $this->storageInstances[$uid];
176  }
177 
183  protected function emitPostProcessStorageSignal(ResourceStorage $storageObject)
184  {
185  $this->signalSlotDispatcher->dispatch(\TYPO3\CMS\Core\Resource\ResourceFactory::class, self::SIGNAL_PostProcessStorage, [$this, $storageObject]);
186  }
187 
198  protected function findBestMatchingStorageByLocalPath(&$localPath)
199  {
200  if ($this->localDriverStorageCache === null) {
201  $this->initializeLocalStorageCache();
202  }
203 
204  $bestMatchStorageUid = 0;
205  $bestMatchLength = 0;
206  foreach ($this->localDriverStorageCache as $storageUid => $basePath) {
207  $matchLength = strlen(PathUtility::getCommonPrefix([$basePath, $localPath]));
208  $basePathLength = strlen($basePath);
209 
210  if ($matchLength >= $basePathLength && $matchLength > $bestMatchLength) {
211  $bestMatchStorageUid = (int)$storageUid;
212  $bestMatchLength = $matchLength;
213  }
214  }
215  if ($bestMatchStorageUid !== 0) {
216  $localPath = substr($localPath, $bestMatchLength);
217  }
218  return $bestMatchStorageUid;
219  }
220 
226  protected function initializeLocalStorageCache()
227  {
229  $storageRepository = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class);
231  $storageObjects = $storageRepository->findByStorageType('Local');
232 
233  $storageCache = [];
234  foreach ($storageObjects as $localStorage) {
235  $configuration = $localStorage->getConfiguration();
236  $storageCache[$localStorage->getUid()] = $configuration['basePath'];
237  }
238  $this->localDriverStorageCache = $storageCache;
239  }
240 
247  public function convertFlexFormDataToConfigurationArray($flexFormData)
248  {
249  $configuration = [];
250  if ($flexFormData) {
251  $flexFormService = GeneralUtility::makeInstance(FlexFormService::class);
252  $configuration = $flexFormService->convertFlexFormContentToArray($flexFormData);
253  }
254  return $configuration;
255  }
256 
266  public function getCollectionObject($uid, array $recordData = [])
267  {
268  if (!is_numeric($uid)) {
269  throw new \InvalidArgumentException('The UID of collection has to be numeric. UID given: "' . $uid . '"', 1314085999);
270  }
271  if (!$this->collectionInstances[$uid]) {
272  // Get mount data if not already supplied as argument to this function
273  if (empty($recordData) || $recordData['uid'] !== $uid) {
275  $recordData = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', 'sys_file_collection', 'uid=' . (int)$uid . ' AND deleted=0');
276  if (!is_array($recordData)) {
277  throw new \InvalidArgumentException('No collection found for given UID: "' . $uid . '"', 1314085992);
278  }
279  }
280  $collectionObject = $this->createCollectionObject($recordData);
281  $this->collectionInstances[$uid] = $collectionObject;
282  }
283  return $this->collectionInstances[$uid];
284  }
285 
292  public function createCollectionObject(array $collectionData)
293  {
295  $registry = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\Collection\FileCollectionRegistry::class);
296  $class = $registry->getFileCollectionClass($collectionData['type']);
297 
298  return $class::create($collectionData);
299  }
300 
308  public function createStorageObject(array $storageRecord, array $storageConfiguration = null)
309  {
310  $className = \TYPO3\CMS\Core\Resource\ResourceStorage::class;
311  if (!$storageConfiguration) {
312  $storageConfiguration = $this->convertFlexFormDataToConfigurationArray($storageRecord['configuration']);
313  }
314  $driverType = $storageRecord['driver'];
315  $driverObject = $this->getDriverObject($driverType, $storageConfiguration);
316  return GeneralUtility::makeInstance($className, $driverObject, $storageRecord);
317  }
318 
327  public function createFolderObject(ResourceStorage $storage, $identifier, $name)
328  {
329  return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\Folder::class, $storage, $identifier, $name);
330  }
331 
343  public function getFileObject($uid, array $fileData = [])
344  {
345  if (!is_numeric($uid)) {
346  throw new \InvalidArgumentException('The UID of file has to be numeric. UID given: "' . $uid . '"', 1300096564);
347  }
348  if (!$this->fileInstances[$uid]) {
349  // Fetches data in case $fileData is empty
350  if (empty($fileData)) {
351  $fileData = $this->getFileIndexRepository()->findOneByUid($uid);
352  if ($fileData === false) {
353  throw new \TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException('No file found for given UID: ' . $uid, 1317178604);
354  }
355  }
356  $this->fileInstances[$uid] = $this->createFileObject($fileData);
357  }
358  return $this->fileInstances[$uid];
359  }
360 
368  public function getFileObjectFromCombinedIdentifier($identifier)
369  {
370  if (!isset($identifier) || !is_string($identifier) || $identifier === '') {
371  throw new \InvalidArgumentException('Invalid file identifier given. It must be of type string and not empty. "' . gettype($identifier) . '" given.', 1401732564);
372  }
373  $parts = GeneralUtility::trimExplode(':', $identifier);
374  if (count($parts) === 2) {
375  $storageUid = $parts[0];
376  $fileIdentifier = $parts[1];
377  } else {
378  // We only got a path: Go into backwards compatibility mode and
379  // use virtual Storage (uid=0)
380  $storageUid = 0;
381  $fileIdentifier = $parts[0];
382  }
383 
384  // please note that getStorageObject() might modify $fileIdentifier when
385  // auto-detecting the best-matching storage to use
386  return $this->getFileObjectByStorageAndIdentifier($storageUid, $fileIdentifier);
387  }
388 
398  public function getFileObjectByStorageAndIdentifier($storageUid, &$fileIdentifier)
399  {
400  $storage = $this->getStorageObject($storageUid, [], $fileIdentifier);
401  if (!$storage->isWithinProcessingFolder($fileIdentifier)) {
402  $fileData = $this->getFileIndexRepository()->findOneByStorageUidAndIdentifier($storage->getUid(), $fileIdentifier);
403  if ($fileData === false) {
404  $fileObject = $this->getIndexer($storage)->createIndexEntry($fileIdentifier);
405  } else {
406  $fileObject = $this->getFileObject($fileData['uid'], $fileData);
407  }
408  } else {
409  $fileObject = $this->getProcessedFileRepository()->findByStorageAndIdentifier($storage, $fileIdentifier);
410  }
411 
412  return $fileObject;
413  }
414 
435  public function retrieveFileOrFolderObject($input)
436  {
437  // Remove PATH_site because absolute paths under Windows systems contain ':'
438  // This is done in all considered sub functions anyway
439  $input = str_replace(PATH_site, '', $input);
440 
441  if (GeneralUtility::isFirstPartOfStr($input, 'file:')) {
442  $input = substr($input, 5);
443  return $this->retrieveFileOrFolderObject($input);
444  } elseif (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($input)) {
445  return $this->getFileObject($input);
446  } elseif (strpos($input, ':') > 0) {
447  list($prefix, $folderIdentifier) = explode(':', $input);
448  if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($prefix)) {
449  // path or folder in a valid storageUID
450  return $this->getObjectFromCombinedIdentifier($input);
451  } elseif ($prefix == 'EXT') {
452  $input = GeneralUtility::getFileAbsFileName($input);
453  if (empty($input)) {
454  return null;
455  }
456 
457  $input = PathUtility::getRelativePath(PATH_site, PathUtility::dirname($input)) . PathUtility::basename($input);
458  return $this->getFileObjectFromCombinedIdentifier($input);
459  } else {
460  return null;
461  }
462  } else {
463  // this is a backwards-compatible way to access "0-storage" files or folders
464  // eliminate double slashes, /./ and /../
465  $input = \TYPO3\CMS\Core\Utility\PathUtility::getCanonicalPath(ltrim($input, '/'));
466  if (@is_file(PATH_site . $input)) {
467  // only the local file
468  return $this->getFileObjectFromCombinedIdentifier($input);
469  } else {
470  // only the local path
471  return $this->getFolderObjectFromCombinedIdentifier($input);
472  }
473  }
474  }
475 
483  public function getFolderObjectFromCombinedIdentifier($identifier)
484  {
485  $parts = GeneralUtility::trimExplode(':', $identifier);
486  if (count($parts) === 2) {
487  $storageUid = $parts[0];
488  $folderIdentifier = $parts[1];
489  } else {
490  // We only got a path: Go into backwards compatibility mode and
491  // use virtual Storage (uid=0)
492  $storageUid = 0;
493 
494  // please note that getStorageObject() might modify $folderIdentifier when
495  // auto-detecting the best-matching storage to use
496  $folderIdentifier = $parts[0];
497  // make sure to not use an absolute path, and remove PATH_site if it is prepended
498  if (GeneralUtility::isFirstPartOfStr($folderIdentifier, PATH_site)) {
499  $folderIdentifier = \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($parts[0]);
500  }
501  }
502  return $this->getStorageObject($storageUid, [], $folderIdentifier)->getFolder($folderIdentifier);
503  }
504 
511  public function getStorageObjectFromCombinedIdentifier($identifier)
512  {
513  $parts = GeneralUtility::trimExplode(':', $identifier);
514  $storageUid = count($parts) === 2 ? $parts[0] : null;
515  return $this->getStorageObject($storageUid);
516  }
517 
526  public function getObjectFromCombinedIdentifier($identifier)
527  {
528  list($storageId, $objectIdentifier) = GeneralUtility::trimExplode(':', $identifier);
529  $storage = $this->getStorageObject($storageId);
530  if ($storage->hasFile($objectIdentifier)) {
531  return $storage->getFile($objectIdentifier);
532  } elseif ($storage->hasFolder($objectIdentifier)) {
533  return $storage->getFolder($objectIdentifier);
534  } else {
535  throw new \TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException('Object with identifier "' . $identifier . '" does not exist in storage', 1329647780);
536  }
537  }
538 
547  public function createFileObject(array $fileData, ResourceStorage $storage = null)
548  {
550  if (array_key_exists('storage', $fileData) && MathUtility::canBeInterpretedAsInteger($fileData['storage'])) {
551  $storageObject = $this->getStorageObject((int)$fileData['storage']);
552  } elseif ($storage !== null) {
553  $storageObject = $storage;
554  $fileData['storage'] = $storage->getUid();
555  } else {
556  throw new \RuntimeException('A file needs to reside in a Storage', 1381570997);
557  }
558  $fileObject = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\File::class, $fileData, $storageObject);
559  return $fileObject;
560  }
561 
573  public function getFileReferenceObject($uid, array $fileReferenceData = [], $raw = false)
574  {
575  if (!is_numeric($uid)) {
576  throw new \InvalidArgumentException(
577  'The reference UID for the file (sys_file_reference) has to be numeric. UID given: "' . $uid . '"',
578  1300086584
579  );
580  }
581  if (!$this->fileReferenceInstances[$uid]) {
582  // Fetches data in case $fileData is empty
583  if (empty($fileReferenceData)) {
584  $fileReferenceData = $this->getFileReferenceData($uid, $raw);
585  if (!is_array($fileReferenceData)) {
586  throw new \TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException(
587  'No file reference (sys_file_reference) was found for given UID: "' . $uid . '"',
588  1317178794
589  );
590  }
591  }
592  $this->fileReferenceInstances[$uid] = $this->createFileReferenceObject($fileReferenceData);
593  }
594  return $this->fileReferenceInstances[$uid];
595  }
596 
605  public function createFileReferenceObject(array $fileReferenceData)
606  {
608  $fileReferenceObject = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\FileReference::class, $fileReferenceData);
609  return $fileReferenceObject;
610  }
611 
619  protected function getFileReferenceData($uid, $raw = false)
620  {
621  if (!$raw && TYPO3_MODE === 'BE') {
622  $fileReferenceData = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecordWSOL('sys_file_reference', $uid);
623  } elseif (!$raw && is_object($GLOBALS['TSFE'])) {
624  $fileReferenceData = $GLOBALS['TSFE']->sys_page->checkRecord('sys_file_reference', $uid);
625  } else {
627  $fileReferenceData = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', 'sys_file_reference', 'uid=' . (int)$uid . ' AND deleted=0');
628  }
629  return $fileReferenceData;
630  }
631 
637  protected function getFileIndexRepository()
638  {
640  }
641 
647  protected function getProcessedFileRepository()
648  {
649  return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\ProcessedFileRepository::class);
650  }
651 
657  protected function getIndexer(ResourceStorage $storage)
658  {
659  return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\Index\Indexer::class, $storage);
660  }
661 }
static getCommonPrefix(array $paths)
createFolderObject(ResourceStorage $storage, $identifier, $name)
static isFirstPartOfStr($str, $partStr)
createStorageObject(array $storageRecord, array $storageConfiguration=null)
static trimExplode($delim, $string, $removeEmptyValues=false, $limit=0)
__construct(\TYPO3\CMS\Extbase\SignalSlot\Dispatcher $signalSlotDispatcher=null)
$uid
Definition: server.php:38
static getFileAbsFileName($filename, $onlyRelative=true, $relToTYPO3_mainDir=false)
static getRelativePath($sourcePath, $targetPath)
Definition: PathUtility.php:70
emitPostProcessStorageSignal(ResourceStorage $storageObject)
getFileObjectByStorageAndIdentifier($storageUid, &$fileIdentifier)
if(TYPO3_MODE==='BE') $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tsfebeuserauth.php']['frontendEditingController']['default']
static getRecordWSOL($table, $uid, $fields=' *', $where='', $useDeleteClause=true, $unsetMovePointers=false)
getFileReferenceObject($uid, array $fileReferenceData=[], $raw=false)
getFileObject($uid, array $fileData=[])