TYPO3 CMS  TYPO3_6-2
ResourceFactory.php
Go to the documentation of this file.
1 <?php
3 
21 
22 // TODO implement constructor-level caching
29 
35  static public function getInstance() {
36  return GeneralUtility::makeInstance(__CLASS__);
37  }
38 
42  protected $storageInstances = array();
43 
47  protected $collectionInstances = array();
48 
52  protected $fileInstances = array();
53 
57  protected $fileReferenceInstances = array();
58 
64  protected $localDriverStorageCache = NULL;
65 
70 
74  public function __construct(\TYPO3\CMS\Extbase\SignalSlot\Dispatcher $signalSlotDispatcher = NULL) {
75  $this->signalSlotDispatcher = $signalSlotDispatcher ?: GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\SignalSlot\\Dispatcher');
76  }
77 
86  public function getDriverObject($driverIdentificationString, array $driverConfiguration) {
88  $driverRegistry = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\Driver\\DriverRegistry');
89  $driverClass = $driverRegistry->getDriverClass($driverIdentificationString);
90  $driverObject = GeneralUtility::makeInstance($driverClass, $driverConfiguration);
91  return $driverObject;
92  }
93 
94 
105  public function getDefaultStorage() {
107  $storageRepository = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\StorageRepository');
108 
109  $allStorages = $storageRepository->findAll();
110  foreach ($allStorages as $storage) {
111  if ($storage->isDefault()) {
112  return $storage;
113  }
114  }
115  return NULL;
116  }
128  public function getStorageObject($uid, array $recordData = array(), &$fileIdentifier = NULL) {
129  if (!is_numeric($uid)) {
130  throw new \InvalidArgumentException('uid of Storage has to be numeric.', 1314085991);
131  }
132  $uid = (int)$uid;
133  if ($uid === 0 && $fileIdentifier !== NULL) {
134  $uid = $this->findBestMatchingStorageByLocalPath($fileIdentifier);
135  }
136  if (!$this->storageInstances[$uid]) {
137  $storageConfiguration = NULL;
138  $storageObject = NULL;
139  // If the built-in storage with UID=0 is requested:
140  if ($uid === 0) {
141  $recordData = array(
142  'uid' => 0,
143  'pid' => 0,
144  'name' => 'Fallback Storage',
145  'description' => 'Internal storage, mounting the main TYPO3_site directory.',
146  'driver' => 'Local',
147  'processingfolder' => 'typo3temp/_processed_/',
148  // legacy code
149  'configuration' => '',
150  'is_online' => TRUE,
151  'is_browsable' => TRUE,
152  'is_public' => TRUE,
153  'is_writable' => TRUE,
154  'is_default' => FALSE,
155  );
156  $storageConfiguration = array(
157  'basePath' => '/',
158  'pathType' => 'relative'
159  );
160  } elseif (count($recordData) === 0 || (int)$recordData['uid'] !== $uid) {
162  $storageRepository = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\StorageRepository');
164  $storageObject = $storageRepository->findByUid($uid);
165  }
166  if (!$storageObject instanceof ResourceStorage) {
167  $storageObject = $this->createStorageObject($recordData, $storageConfiguration);
168  }
169  $this->emitPostProcessStorageSignal($storageObject);
170  $this->storageInstances[$uid] = $storageObject;
171  }
172  return $this->storageInstances[$uid];
173  }
174 
180  protected function emitPostProcessStorageSignal(ResourceStorage $storageObject) {
181  $this->signalSlotDispatcher->dispatch('TYPO3\\CMS\\Core\\Resource\\ResourceFactory', self::SIGNAL_PostProcessStorage, array($this, $storageObject));
182  }
183 
194  protected function findBestMatchingStorageByLocalPath(&$localPath) {
195  if ($this->localDriverStorageCache === NULL) {
196  $this->initializeLocalStorageCache();
197  }
198 
199  $bestMatchStorageUid = 0;
200  $bestMatchLength = 0;
201  foreach ($this->localDriverStorageCache as $storageUid => $basePath) {
202  $matchLength = strlen(PathUtility::getCommonPrefix(array($basePath, $localPath)));
203  $basePathLength = strlen($basePath);
204 
205  if ($matchLength >= $basePathLength && $matchLength > $bestMatchLength) {
206  $bestMatchStorageUid = (int)$storageUid;
207  $bestMatchLength = $matchLength;
208  }
209  }
210  if ($bestMatchStorageUid !== 0) {
211  $localPath = substr($localPath, $bestMatchLength);
212  }
213  return $bestMatchStorageUid;
214  }
215 
221  protected function initializeLocalStorageCache() {
223  $storageRepository = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\StorageRepository');
225  $storageObjects = $storageRepository->findByStorageType('Local');
226 
227  $storageCache = array();
228  foreach ($storageObjects as $localStorage) {
229  $configuration = $localStorage->getConfiguration();
230  $storageCache[$localStorage->getUid()] = $configuration['basePath'];
231  }
232  $this->localDriverStorageCache = $storageCache;
233  }
234 
241  public function convertFlexFormDataToConfigurationArray($flexFormData) {
242  $configuration = array();
243  if ($flexFormData) {
244  $flexFormContents = GeneralUtility::xml2array($flexFormData);
245  if (!empty($flexFormContents['data']['sDEF']['lDEF']) && is_array($flexFormContents['data']['sDEF']['lDEF'])) {
246  foreach ($flexFormContents['data']['sDEF']['lDEF'] as $key => $value) {
247  if (isset($value['vDEF'])) {
248  $configuration[$key] = $value['vDEF'];
249  }
250  }
251  }
252  }
253  return $configuration;
254  }
255 
265  public function getCollectionObject($uid, array $recordData = array()) {
266  if (!is_numeric($uid)) {
267  throw new \InvalidArgumentException('uid of collection has to be numeric.', 1314085999);
268  }
269  if (!$this->collectionInstances[$uid]) {
270  // Get mount data if not already supplied as argument to this function
271  if (count($recordData) === 0 || $recordData['uid'] !== $uid) {
273  $recordData = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', 'sys_file_collection', 'uid=' . (int)$uid . ' AND deleted=0');
274  if (!is_array($recordData)) {
275  throw new \InvalidArgumentException('No collection found for given UID.', 1314085992);
276  }
277  }
278  $collectionObject = $this->createCollectionObject($recordData);
279  $this->collectionInstances[$uid] = $collectionObject;
280  }
281  return $this->collectionInstances[$uid];
282  }
283 
290  public function createCollectionObject(array $collectionData) {
292  $registry = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\Collection\\FileCollectionRegistry');
293  $class = $registry->getFileCollectionClass($collectionData['type']);
294 
295  return $class::create($collectionData);
296  }
297 
305  public function createStorageObject(array $storageRecord, array $storageConfiguration = NULL) {
306  $className = 'TYPO3\\CMS\\Core\\Resource\\ResourceStorage';
307  if (!$storageConfiguration) {
308  $storageConfiguration = $this->convertFlexFormDataToConfigurationArray($storageRecord['configuration']);
309  }
310  $driverType = $storageRecord['driver'];
311  $driverObject = $this->getDriverObject($driverType, $storageConfiguration);
312  return GeneralUtility::makeInstance($className, $driverObject, $storageRecord);
313  }
314 
323  public function createFolderObject(ResourceStorage $storage, $identifier, $name) {
324  return GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\Folder', $storage, $identifier, $name);
325  }
326 
338  public function getFileObject($uid, array $fileData = array()) {
339  if (!is_numeric($uid)) {
340  throw new \InvalidArgumentException('uid of file has to be numeric.', 1300096564);
341  }
342  if (!$this->fileInstances[$uid]) {
343  // Fetches data in case $fileData is empty
344  if (empty($fileData)) {
345  $fileData = $this->getFileIndexRepository()->findOneByUid($uid);
346  if ($fileData === FALSE) {
347  throw new \TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException('No file found for given UID.', 1317178604);
348  }
349  }
350  $this->fileInstances[$uid] = $this->createFileObject($fileData);
351  }
352  return $this->fileInstances[$uid];
353  }
354 
362  public function getFileObjectFromCombinedIdentifier($identifier) {
363  if (!isset($identifier) || !is_string($identifier) || $identifier === '') {
364  throw new \InvalidArgumentException('Invalid file identifier given. It must be of type string and not empty. "' . gettype($identifier) . '" given.', 1401732564);
365  }
366  $parts = GeneralUtility::trimExplode(':', $identifier);
367  if (count($parts) === 2) {
368  $storageUid = $parts[0];
369  $fileIdentifier = $parts[1];
370  } else {
371  // We only got a path: Go into backwards compatibility mode and
372  // use virtual Storage (uid=0)
373  $storageUid = 0;
374  $fileIdentifier = $parts[0];
375  }
376 
377  // please note that getStorageObject() might modify $fileIdentifier when
378  // auto-detecting the best-matching storage to use
379  return $this->getFileObjectByStorageAndIdentifier($storageUid, $fileIdentifier);
380  }
381 
391  public function getFileObjectByStorageAndIdentifier($storageUid, &$fileIdentifier) {
392  $storage = $this->getStorageObject($storageUid, array(), $fileIdentifier);
393  if (!$storage->isWithinProcessingFolder($fileIdentifier)) {
394  $fileData = $this->getFileIndexRepository()->findOneByStorageUidAndIdentifier($storage->getUid(), $fileIdentifier);
395  if ($fileData === FALSE) {
396  $fileObject = $this->getIndexer($storage)->createIndexEntry($fileIdentifier);
397  } else {
398  $fileObject = $this->getFileObject($fileData['uid'], $fileData);
399  }
400  } else {
401  $fileObject = $this->getProcessedFileRepository()->findByStorageAndIdentifier($storage, $fileIdentifier);
402  }
403 
404  return $fileObject;
405  }
406 
427  public function retrieveFileOrFolderObject($input) {
428  // Remove PATH_site because absolute paths under Windows systems contain ':'
429  // This is done in all considered sub functions anyway
430  $input = str_replace(PATH_site, '', $input);
431 
432  if (GeneralUtility::isFirstPartOfStr($input, 'file:')) {
433  $input = substr($input, 5);
434  return $this->retrieveFileOrFolderObject($input);
435  } elseif (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($input)) {
436  return $this->getFileObject($input);
437  } elseif (strpos($input, ':') > 0) {
438  list($prefix, $folderIdentifier) = explode(':', $input);
439  if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($prefix)) {
440  // path or folder in a valid storageUID
441  return $this->getObjectFromCombinedIdentifier($input);
442  } elseif ($prefix == 'EXT') {
443  $input = GeneralUtility::getFileAbsFileName($input);
444  if (empty($input)) {
445  return NULL;
446  }
447  $input = PathUtility::getRelativePath(PATH_site, dirname($input)) . basename($input);
448  return $this->getFileObjectFromCombinedIdentifier($input);
449  } else {
450  return NULL;
451  }
452  } else {
453  // this is a backwards-compatible way to access "0-storage" files or folders
454  // eliminate double slashes, /./ and /../
455  $input = \TYPO3\CMS\Core\Utility\PathUtility::getCanonicalPath(ltrim($input, '/'));
456  if (@is_file(PATH_site . $input)) {
457  // only the local file
458  return $this->getFileObjectFromCombinedIdentifier($input);
459  } else {
460  // only the local path
461  return $this->getFolderObjectFromCombinedIdentifier($input);
462  }
463  }
464  }
465 
473  public function getFolderObjectFromCombinedIdentifier($identifier) {
474  $parts = GeneralUtility::trimExplode(':', $identifier);
475  if (count($parts) === 2) {
476  $storageUid = $parts[0];
477  $folderIdentifier = $parts[1];
478  } else {
479  // We only got a path: Go into backwards compatibility mode and
480  // use virtual Storage (uid=0)
481  $storageUid = 0;
482 
483  // please note that getStorageObject() might modify $folderIdentifier when
484  // auto-detecting the best-matching storage to use
485  $folderIdentifier = $parts[0];
486  // make sure to not use an absolute path, and remove PATH_site if it is prepended
487  if (GeneralUtility::isFirstPartOfStr($folderIdentifier, PATH_site)) {
488  $folderIdentifier = \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($parts[0]);
489  }
490  }
491  return $this->getStorageObject($storageUid, array(), $folderIdentifier)->getFolder($folderIdentifier);
492  }
493 
500  public function getStorageObjectFromCombinedIdentifier($identifier) {
501  $parts = GeneralUtility::trimExplode(':', $identifier);
502  $storageUid = count($parts) === 2 ? $parts[0] : NULL;
503  return $this->getStorageObject($storageUid);
504  }
505 
514  public function getObjectFromCombinedIdentifier($identifier) {
515  list($storageId, $objectIdentifier) = GeneralUtility::trimExplode(':', $identifier);
516  $storage = $this->getStorageObject($storageId);
517  if ($storage->hasFile($objectIdentifier)) {
518  return $storage->getFile($objectIdentifier);
519  } elseif ($storage->hasFolder($objectIdentifier)) {
520  return $storage->getFolder($objectIdentifier);
521  } else {
522  throw new \TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException('Object with identifier "' . $identifier . '" does not exist in storage', 1329647780);
523  }
524  }
525 
534  public function createFileObject(array $fileData, ResourceStorage $storage = NULL) {
536  if (array_key_exists('storage', $fileData) && MathUtility::canBeInterpretedAsInteger($fileData['storage'])) {
537  $storageObject = $this->getStorageObject((int)$fileData['storage']);
538  } elseif ($storage !== NULL) {
539  $storageObject = $storage;
540  $fileData['storage'] = $storage->getUid();
541  } else {
542  throw new \RuntimeException('A file needs to reside in a Storage', 1381570997);
543  }
544  $fileObject = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\File', $fileData, $storageObject);
545  return $fileObject;
546  }
547 
559  public function getFileReferenceObject($uid, array $fileReferenceData = array(), $raw = FALSE) {
560  if (!is_numeric($uid)) {
561  throw new \InvalidArgumentException('uid of file usage (sys_file_reference) has to be numeric.', 1300086584);
562  }
563  if (!$this->fileReferenceInstances[$uid]) {
564  // Fetches data in case $fileData is empty
565  if (empty($fileReferenceData)) {
566  $fileReferenceData = $this->getFileReferenceData($uid, $raw);
567  if (!is_array($fileReferenceData)) {
568  throw new \TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException('No file usage (sys_file_reference) found for given UID.', 1317178794);
569  }
570  }
571  $this->fileReferenceInstances[$uid] = $this->createFileReferenceObject($fileReferenceData);
572  }
573  return $this->fileReferenceInstances[$uid];
574  }
575 
584  public function createFileReferenceObject(array $fileReferenceData) {
586  $fileReferenceObject = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\FileReference', $fileReferenceData);
587  return $fileReferenceObject;
588  }
589 
597  protected function getFileReferenceData($uid, $raw = FALSE) {
598  if (!$raw && TYPO3_MODE === 'BE') {
599  $fileReferenceData = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecordWSOL('sys_file_reference', $uid);
600  } elseif (!$raw && is_object($GLOBALS['TSFE'])) {
601  $fileReferenceData = $GLOBALS['TSFE']->sys_page->checkRecord('sys_file_reference', $uid);
602  } else {
604  $fileReferenceData = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', 'sys_file_reference', 'uid=' . (int)$uid . ' AND deleted=0');
605  }
606  return $fileReferenceData;
607  }
608 
614  protected function getFileIndexRepository() {
616  }
617 
623  protected function getProcessedFileRepository() {
624  return GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\ProcessedFileRepository');
625  }
626 
632  protected function getIndexer(ResourceStorage $storage) {
633  return GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\Index\\Indexer', $storage);
634  }
635 
636 }
static getRecordWSOL($table, $uid, $fields=' *', $where='', $useDeleteClause=TRUE, $unsetMovePointers=FALSE)
getFileObject($uid, array $fileData=array())
static getCommonPrefix(array $paths)
createFolderObject(ResourceStorage $storage, $identifier, $name)
static isFirstPartOfStr($str, $partStr)
$uid
Definition: server.php:36
const TYPO3_MODE
Definition: init.php:40
createStorageObject(array $storageRecord, array $storageConfiguration=NULL)
static trimExplode($delim, $string, $removeEmptyValues=FALSE, $limit=0)
$registry
Definition: ext_tables.php:46
__construct(\TYPO3\CMS\Extbase\SignalSlot\Dispatcher $signalSlotDispatcher=NULL)
getFileReferenceObject($uid, array $fileReferenceData=array(), $raw=FALSE)
static getRelativePath($sourcePath, $targetPath)
Definition: PathUtility.php:71
if(!defined('TYPO3_MODE')) $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_pre_processing'][]
emitPostProcessStorageSignal(ResourceStorage $storageObject)
getFileObjectByStorageAndIdentifier($storageUid, &$fileIdentifier)
static xml2array($string, $NSprefix='', $reportDocTag=FALSE)
static getFileAbsFileName($filename, $onlyRelative=TRUE, $relToTYPO3_mainDir=FALSE)