TYPO3  7.6
ResourceFactory.php
Go to the documentation of this file.
1 <?php
2 namespace TYPO3\CMS\Core\Resource;
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 
21 
22 // @todo implement constructor-level caching
27 {
33  public static function getInstance()
34  {
35  return GeneralUtility::makeInstance(__CLASS__);
36  }
37 
41  protected $storageInstances = array();
42 
46  protected $collectionInstances = array();
47 
51  protected $fileInstances = array();
52 
56  protected $fileReferenceInstances = array();
57 
63  protected $localDriverStorageCache = null;
64 
69 
73  public function __construct(\TYPO3\CMS\Extbase\SignalSlot\Dispatcher $signalSlotDispatcher = null)
74  {
75  $this->signalSlotDispatcher = $signalSlotDispatcher ?: GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\SignalSlot\Dispatcher::class);
76  }
77 
86  public function getDriverObject($driverIdentificationString, array $driverConfiguration)
87  {
89  $driverRegistry = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\Driver\DriverRegistry::class);
90  $driverClass = $driverRegistry->getDriverClass($driverIdentificationString);
91  $driverObject = GeneralUtility::makeInstance($driverClass, $driverConfiguration);
92  return $driverObject;
93  }
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 = array(), &$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 = array(
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 = array(
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, array($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(array($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 = array();
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 = array();
250  if ($flexFormData) {
251  $flexFormContents = GeneralUtility::xml2array($flexFormData);
252  if (!empty($flexFormContents['data']['sDEF']['lDEF']) && is_array($flexFormContents['data']['sDEF']['lDEF'])) {
253  foreach ($flexFormContents['data']['sDEF']['lDEF'] as $key => $value) {
254  if (isset($value['vDEF'])) {
255  $configuration[$key] = $value['vDEF'];
256  }
257  }
258  }
259  }
260  return $configuration;
261  }
262 
272  public function getCollectionObject($uid, array $recordData = array())
273  {
274  if (!is_numeric($uid)) {
275  throw new \InvalidArgumentException('The UID of collection has to be numeric. UID given: "' . $uid . '"', 1314085999);
276  }
277  if (!$this->collectionInstances[$uid]) {
278  // Get mount data if not already supplied as argument to this function
279  if (empty($recordData) || $recordData['uid'] !== $uid) {
281  $recordData = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', 'sys_file_collection', 'uid=' . (int)$uid . ' AND deleted=0');
282  if (!is_array($recordData)) {
283  throw new \InvalidArgumentException('No collection found for given UID: "' . $uid . '"', 1314085992);
284  }
285  }
286  $collectionObject = $this->createCollectionObject($recordData);
287  $this->collectionInstances[$uid] = $collectionObject;
288  }
289  return $this->collectionInstances[$uid];
290  }
291 
298  public function createCollectionObject(array $collectionData)
299  {
301  $registry = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\Collection\FileCollectionRegistry::class);
302  $class = $registry->getFileCollectionClass($collectionData['type']);
303 
304  return $class::create($collectionData);
305  }
306 
314  public function createStorageObject(array $storageRecord, array $storageConfiguration = null)
315  {
316  $className = \TYPO3\CMS\Core\Resource\ResourceStorage::class;
317  if (!$storageConfiguration) {
318  $storageConfiguration = $this->convertFlexFormDataToConfigurationArray($storageRecord['configuration']);
319  }
320  $driverType = $storageRecord['driver'];
321  $driverObject = $this->getDriverObject($driverType, $storageConfiguration);
322  return GeneralUtility::makeInstance($className, $driverObject, $storageRecord);
323  }
324 
333  public function createFolderObject(ResourceStorage $storage, $identifier, $name)
334  {
335  return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\Folder::class, $storage, $identifier, $name);
336  }
337 
349  public function getFileObject($uid, array $fileData = array())
350  {
351  if (!is_numeric($uid)) {
352  throw new \InvalidArgumentException('The UID of file has to be numeric. UID given: "' . $uid . '"', 1300096564);
353  }
354  if (!$this->fileInstances[$uid]) {
355  // Fetches data in case $fileData is empty
356  if (empty($fileData)) {
357  $fileData = $this->getFileIndexRepository()->findOneByUid($uid);
358  if ($fileData === false) {
359  throw new \TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException('No file found for given UID:' . $uid, 1317178604);
360  }
361  }
362  $this->fileInstances[$uid] = $this->createFileObject($fileData);
363  }
364  return $this->fileInstances[$uid];
365  }
366 
374  public function getFileObjectFromCombinedIdentifier($identifier)
375  {
376  if (!isset($identifier) || !is_string($identifier) || $identifier === '') {
377  throw new \InvalidArgumentException('Invalid file identifier given. It must be of type string and not empty. "' . gettype($identifier) . '" given.', 1401732564);
378  }
379  $parts = GeneralUtility::trimExplode(':', $identifier);
380  if (count($parts) === 2) {
381  $storageUid = $parts[0];
382  $fileIdentifier = $parts[1];
383  } else {
384  // We only got a path: Go into backwards compatibility mode and
385  // use virtual Storage (uid=0)
386  $storageUid = 0;
387  $fileIdentifier = $parts[0];
388  }
389 
390  // please note that getStorageObject() might modify $fileIdentifier when
391  // auto-detecting the best-matching storage to use
392  return $this->getFileObjectByStorageAndIdentifier($storageUid, $fileIdentifier);
393  }
394 
404  public function getFileObjectByStorageAndIdentifier($storageUid, &$fileIdentifier)
405  {
406  $storage = $this->getStorageObject($storageUid, array(), $fileIdentifier);
407  if (!$storage->isWithinProcessingFolder($fileIdentifier)) {
408  $fileData = $this->getFileIndexRepository()->findOneByStorageUidAndIdentifier($storage->getUid(), $fileIdentifier);
409  if ($fileData === false) {
410  $fileObject = $this->getIndexer($storage)->createIndexEntry($fileIdentifier);
411  } else {
412  $fileObject = $this->getFileObject($fileData['uid'], $fileData);
413  }
414  } else {
415  $fileObject = $this->getProcessedFileRepository()->findByStorageAndIdentifier($storage, $fileIdentifier);
416  }
417 
418  return $fileObject;
419  }
420 
441  public function retrieveFileOrFolderObject($input)
442  {
443  // Remove PATH_site because absolute paths under Windows systems contain ':'
444  // This is done in all considered sub functions anyway
445  $input = str_replace(PATH_site, '', $input);
446 
447  if (GeneralUtility::isFirstPartOfStr($input, 'file:')) {
448  $input = substr($input, 5);
449  return $this->retrieveFileOrFolderObject($input);
450  } elseif (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($input)) {
451  return $this->getFileObject($input);
452  } elseif (strpos($input, ':') > 0) {
453  list($prefix, $folderIdentifier) = explode(':', $input);
454  if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($prefix)) {
455  // path or folder in a valid storageUID
456  return $this->getObjectFromCombinedIdentifier($input);
457  } elseif ($prefix == 'EXT') {
458  $input = GeneralUtility::getFileAbsFileName($input);
459  if (empty($input)) {
460  return null;
461  }
462 
463  $input = PathUtility::getRelativePath(PATH_site, PathUtility::dirname($input)) . PathUtility::basename($input);
464  return $this->getFileObjectFromCombinedIdentifier($input);
465  } else {
466  return null;
467  }
468  } else {
469  // this is a backwards-compatible way to access "0-storage" files or folders
470  // eliminate double slashes, /./ and /../
471  $input = \TYPO3\CMS\Core\Utility\PathUtility::getCanonicalPath(ltrim($input, '/'));
472  if (@is_file(PATH_site . $input)) {
473  // only the local file
474  return $this->getFileObjectFromCombinedIdentifier($input);
475  } else {
476  // only the local path
477  return $this->getFolderObjectFromCombinedIdentifier($input);
478  }
479  }
480  }
481 
489  public function getFolderObjectFromCombinedIdentifier($identifier)
490  {
491  $parts = GeneralUtility::trimExplode(':', $identifier);
492  if (count($parts) === 2) {
493  $storageUid = $parts[0];
494  $folderIdentifier = $parts[1];
495  } else {
496  // We only got a path: Go into backwards compatibility mode and
497  // use virtual Storage (uid=0)
498  $storageUid = 0;
499 
500  // please note that getStorageObject() might modify $folderIdentifier when
501  // auto-detecting the best-matching storage to use
502  $folderIdentifier = $parts[0];
503  // make sure to not use an absolute path, and remove PATH_site if it is prepended
504  if (GeneralUtility::isFirstPartOfStr($folderIdentifier, PATH_site)) {
505  $folderIdentifier = \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($parts[0]);
506  }
507  }
508  return $this->getStorageObject($storageUid, array(), $folderIdentifier)->getFolder($folderIdentifier);
509  }
510 
517  public function getStorageObjectFromCombinedIdentifier($identifier)
518  {
519  $parts = GeneralUtility::trimExplode(':', $identifier);
520  $storageUid = count($parts) === 2 ? $parts[0] : null;
521  return $this->getStorageObject($storageUid);
522  }
523 
532  public function getObjectFromCombinedIdentifier($identifier)
533  {
534  list($storageId, $objectIdentifier) = GeneralUtility::trimExplode(':', $identifier);
535  $storage = $this->getStorageObject($storageId);
536  if ($storage->hasFile($objectIdentifier)) {
537  return $storage->getFile($objectIdentifier);
538  } elseif ($storage->hasFolder($objectIdentifier)) {
539  return $storage->getFolder($objectIdentifier);
540  } else {
541  throw new \TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException('Object with identifier "' . $identifier . '" does not exist in storage', 1329647780);
542  }
543  }
544 
553  public function createFileObject(array $fileData, ResourceStorage $storage = null)
554  {
556  if (array_key_exists('storage', $fileData) && MathUtility::canBeInterpretedAsInteger($fileData['storage'])) {
557  $storageObject = $this->getStorageObject((int)$fileData['storage']);
558  } elseif ($storage !== null) {
559  $storageObject = $storage;
560  $fileData['storage'] = $storage->getUid();
561  } else {
562  throw new \RuntimeException('A file needs to reside in a Storage', 1381570997);
563  }
564  $fileObject = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\File::class, $fileData, $storageObject);
565  return $fileObject;
566  }
567 
579  public function getFileReferenceObject($uid, array $fileReferenceData = array(), $raw = false)
580  {
581  if (!is_numeric($uid)) {
582  throw new \InvalidArgumentException(
583  'The reference UID for the file (sys_file_reference) has to be numeric. UID given: "' . $uid . '"',
584  1300086584
585  );
586  }
587  if (!$this->fileReferenceInstances[$uid]) {
588  // Fetches data in case $fileData is empty
589  if (empty($fileReferenceData)) {
590  $fileReferenceData = $this->getFileReferenceData($uid, $raw);
591  if (!is_array($fileReferenceData)) {
592  throw new \TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException(
593  'No file reference (sys_file_reference) was found for given UID: "' . $uid . '"',
594  1317178794
595  );
596  }
597  }
598  $this->fileReferenceInstances[$uid] = $this->createFileReferenceObject($fileReferenceData);
599  }
600  return $this->fileReferenceInstances[$uid];
601  }
602 
611  public function createFileReferenceObject(array $fileReferenceData)
612  {
614  $fileReferenceObject = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\FileReference::class, $fileReferenceData);
615  return $fileReferenceObject;
616  }
617 
625  protected function getFileReferenceData($uid, $raw = false)
626  {
627  if (!$raw && TYPO3_MODE === 'BE') {
628  $fileReferenceData = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecordWSOL('sys_file_reference', $uid);
629  } elseif (!$raw && is_object($GLOBALS['TSFE'])) {
630  $fileReferenceData = $GLOBALS['TSFE']->sys_page->checkRecord('sys_file_reference', $uid);
631  } else {
633  $fileReferenceData = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', 'sys_file_reference', 'uid=' . (int)$uid . ' AND deleted=0');
634  }
635  return $fileReferenceData;
636  }
637 
643  protected function getFileIndexRepository()
644  {
646  }
647 
653  protected function getProcessedFileRepository()
654  {
655  return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\ProcessedFileRepository::class);
656  }
657 
663  protected function getIndexer(ResourceStorage $storage)
664  {
665  return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\Index\Indexer::class, $storage);
666  }
667 }