[BUGFIX] Image rendering of non-existing files throws exception
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Resource / ResourceFactory.php
1 <?php
2 namespace TYPO3\CMS\Core\Resource;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 2011-2013 Andreas Wolf <andreas.wolf@typo3.org>
8 * All rights reserved
9 *
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 * A copy is found in the textfile GPL.txt and important notices to the license
19 * from the author is found in LICENSE.txt distributed with these scripts.
20 *
21 *
22 * This script is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * This copyright notice MUST APPEAR in all copies of the script!
28 ***************************************************************/
29 // TODO implement constructor-level caching
30 /**
31 * Factory class for FAL objects.
32 *
33 * NOTE: This class is part of the lowlevel FAL API and should not be used from outside the FAL package.
34 *
35 * @author Andreas Wolf <andreas.wolf@typo3.org>
36 */
37 class ResourceFactory implements \TYPO3\CMS\Core\SingletonInterface {
38
39 /**
40 * Gets a singleton instance of this class.
41 *
42 * @return ResourceFactory
43 */
44 static public function getInstance() {
45 return \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\ResourceFactory');
46 }
47
48 /**
49 * @var ResourceStorage[]
50 */
51 protected $storageInstances = array();
52
53 /**
54 * @var Collection\AbstractFileCollection[]
55 */
56 protected $collectionInstances = array();
57
58 /**
59 * @var File[]
60 */
61 protected $fileInstances = array();
62
63 /**
64 * @var FileReference[]
65 */
66 protected $fileReferenceInstances = array();
67
68 /**
69 * Creates a driver object for a specified storage object.
70 *
71 * @param string $driverIdentificationString The driver class (or identifier) to use.
72 * @param array $driverConfiguration The configuration of the storage
73 * @return Driver\AbstractDriver
74 * @throws \InvalidArgumentException
75 */
76 public function getDriverObject($driverIdentificationString, array $driverConfiguration) {
77 /** @var $driverRegistry Driver\DriverRegistry */
78 $driverRegistry = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\Driver\\DriverRegistry');
79 $driverClass = $driverRegistry->getDriverClass($driverIdentificationString);
80 $driverObject = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance($driverClass, $driverConfiguration);
81 return $driverObject;
82 }
83
84 /**
85 * Creates an instance of the storage from given UID. The $recordData can
86 * be supplied to increase performance.
87 *
88 * @param integer $uid The uid of the storage to instantiate.
89 * @param array $recordData The record row from database.
90 *
91 * @throws \InvalidArgumentException
92 * @return ResourceStorage
93 */
94 public function getStorageObject($uid, array $recordData = array()) {
95 if (!is_numeric($uid)) {
96 throw new \InvalidArgumentException('uid of Storage has to be numeric.', 1314085991);
97 }
98 if (!$this->storageInstances[$uid]) {
99 $storageConfiguration = NULL;
100 $storageObject = NULL;
101 // If the built-in storage with UID=0 is requested:
102 if (intval($uid) === 0) {
103 $recordData = array(
104 'uid' => 0,
105 'pid' => 0,
106 'name' => 'Default Storage',
107 'description' => 'Internal storage, mounting the main TYPO3_site directory.',
108 'driver' => 'Local',
109 'processingfolder' => 'typo3temp/_processed_/',
110 // legacy code
111 'configuration' => '',
112 'is_online' => TRUE,
113 'is_browsable' => TRUE,
114 'is_public' => TRUE,
115 'is_writable' => TRUE
116 );
117 $storageConfiguration = array(
118 'basePath' => '/',
119 'pathType' => 'relative'
120 );
121 } elseif (count($recordData) === 0 || $recordData['uid'] !== $uid) {
122 /** @var $storageRepository StorageRepository */
123 $storageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\StorageRepository');
124 /** @var $storage ResourceStorage */
125 $storageObject = $storageRepository->findByUid($uid);
126 }
127 if (!$storageObject instanceof ResourceStorage) {
128 $storageObject = $this->createStorageObject($recordData, $storageConfiguration);
129 }
130 $this->storageInstances[$uid] = $storageObject;
131 }
132 return $this->storageInstances[$uid];
133 }
134
135 /**
136 * Converts a flexform data string to a flat array with key value pairs
137 *
138 * @param string $flexFormData
139 * @return array Array with key => value pairs of the field data in the FlexForm
140 */
141 public function convertFlexFormDataToConfigurationArray($flexFormData) {
142 $configuration = array();
143 if ($flexFormData) {
144 $flexFormContents = \TYPO3\CMS\Core\Utility\GeneralUtility::xml2array($flexFormData);
145 if (!empty($flexFormContents['data']['sDEF']['lDEF']) && is_array($flexFormContents['data']['sDEF']['lDEF'])) {
146 foreach ($flexFormContents['data']['sDEF']['lDEF'] as $key => $value) {
147 if (isset($value['vDEF'])) {
148 $configuration[$key] = $value['vDEF'];
149 }
150 }
151 }
152 }
153 return $configuration;
154 }
155
156 /**
157 * Creates an instance of the collection from given UID. The $recordData can be supplied to increase performance.
158 *
159 * @param integer $uid The uid of the collection to instantiate.
160 * @param array $recordData The record row from database.
161 *
162 * @throws \InvalidArgumentException
163 * @return Collection\AbstractFileCollection
164 */
165 public function getCollectionObject($uid, array $recordData = array()) {
166 if (!is_numeric($uid)) {
167 throw new \InvalidArgumentException('uid of collection has to be numeric.', 1314085999);
168 }
169 if (!$this->collectionInstances[$uid]) {
170 // Get mount data if not already supplied as argument to this function
171 if (count($recordData) === 0 || $recordData['uid'] !== $uid) {
172 /** @var $GLOBALS['TYPO3_DB'] \TYPO3\CMS\Core\Database\DatabaseConnection */
173 $recordData = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', 'sys_file_collection', 'uid=' . intval($uid) . ' AND deleted=0');
174 if (!is_array($recordData)) {
175 throw new \InvalidArgumentException('No collection found for given UID.', 1314085992);
176 }
177 }
178 $collectionObject = $this->createCollectionObject($recordData);
179 $this->collectionInstances[$uid] = $collectionObject;
180 }
181 return $this->collectionInstances[$uid];
182 }
183
184 /**
185 * Creates a collection object.
186 *
187 * @param array $collectionData The database row of the sys_file_collection record.
188 * @return Collection\AbstractFileCollection
189 */
190 public function createCollectionObject(array $collectionData) {
191 switch ($collectionData['type']) {
192 case 'static':
193 $collection = Collection\StaticFileCollection::create($collectionData);
194 break;
195 case 'folder':
196 $collection = Collection\FolderBasedFileCollection::create($collectionData);
197 break;
198 default:
199 $collection = NULL;
200 }
201 return $collection;
202 }
203
204 /**
205 * Creates a storage object from a storage database row.
206 *
207 * @param array $storageRecord
208 * @param array $storageConfiguration Storage configuration (if given, this won't be extracted from the FlexForm value but the supplied array used instead)
209 * @return ResourceStorage
210 */
211 public function createStorageObject(array $storageRecord, array $storageConfiguration = NULL) {
212 $className = 'TYPO3\\CMS\\Core\\Resource\\ResourceStorage';
213 if (!$storageConfiguration) {
214 $storageConfiguration = $this->convertFlexFormDataToConfigurationArray($storageRecord['configuration']);
215 }
216 $driverType = $storageRecord['driver'];
217 $driverObject = $this->getDriverObject($driverType, $storageConfiguration);
218 /** @var $storage ResourceStorage */
219 $storage = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance($className, $driverObject, $storageRecord);
220 // TODO handle publisher
221 return $storage;
222 }
223
224 /**
225 * Creates a folder to directly access (a part of) a storage.
226 *
227 * @param ResourceStorage $storage The storage the folder belongs to
228 * @param string $identifier The path to the folder. Might also be a simple unique string, depending on the storage driver.
229 * @param string $name The name of the folder (e.g. the folder name)
230 * @return Folder
231 */
232 public function createFolderObject(ResourceStorage $storage, $identifier, $name) {
233 return \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\Folder', $storage, $identifier, $name);
234 }
235
236 protected function createPublisherFromConfiguration(array $configuration) {
237 $publishingTarget = $this->getStorageObject($configuration['publisherConfiguration']['publishingTarget']);
238 $publisher = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance($configuration['publisher'], $publishingTarget, $configuration['publisherConfiguration']);
239 return $publisher;
240 }
241
242 /**
243 * Creates an instance of the file given UID. The $fileData can be supplied
244 * to increase performance.
245 *
246 * @param integer $uid The uid of the file to instantiate.
247 * @param array $fileData The record row from database.
248 *
249 * @throws \InvalidArgumentException
250 * @throws \TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException
251 * @return File
252 */
253 public function getFileObject($uid, array $fileData = array()) {
254 if (!is_numeric($uid)) {
255 throw new \InvalidArgumentException('uid of file has to be numeric.', 1300096564);
256 }
257 if (!$this->fileInstances[$uid]) {
258 // Fetches data in case $fileData is empty
259 if (empty($fileData)) {
260 /** @var $GLOBALS['TYPO3_DB'] \TYPO3\CMS\Core\Database\DatabaseConnection */
261 $fileData = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', 'sys_file', 'uid=' . intval($uid) . ' AND deleted=0');
262 if (!is_array($fileData)) {
263 throw new \TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException('No file found for given UID.', 1317178604);
264 }
265 }
266 $this->fileInstances[$uid] = $this->createFileObject($fileData);
267 }
268 return $this->fileInstances[$uid];
269 }
270
271 /**
272 * Gets an file object from an identifier [storage]:[fileId]
273 *
274 * @param string $identifier
275 * @return File
276 */
277 public function getFileObjectFromCombinedIdentifier($identifier) {
278 $parts = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(':', $identifier);
279 if (count($parts) === 2) {
280 $storageUid = $parts[0];
281 $fileIdentifier = $parts[1];
282 } else {
283 // We only got a path: Go into backwards compatibility mode and
284 // use virtual Storage (uid=0)
285 $storageUid = 0;
286 $fileIdentifier = $parts[0];
287 }
288 return $this->getStorageObject($storageUid)->getFile($fileIdentifier);
289 }
290
291 /**
292 * Bulk function, can be used for anything to get a file or folder
293 *
294 * 1. It's a UID
295 * 2. It's a combined identifier
296 * 3. It's just a path/filename (coming from the oldstyle/backwards compatibility)
297 *
298 * Files, previously laid on fileadmin/ or something, will be "mapped" to the storage the file is
299 * in now. Files like typo3temp/ or typo3conf/ will be moved to the first writable storage
300 * in its processing folder
301 *
302 * $input could be
303 * - "2:myfolder/myfile.jpg" (combined identifier)
304 * - "23" (file UID)
305 * - "uploads/myfile.png" (backwards-compatibility, storage "0")
306 * - "file:23"
307 *
308 * @param string $input
309 * @return FileInterface|Folder
310 */
311 public function retrieveFileOrFolderObject($input) {
312 // Easy function to deal with that, could be dropped in the future
313 // if we know where to use this function
314 if (\TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($input, 'file:')) {
315 $input = substr($input, 5);
316 return $this->retrieveFileOrFolderObject($input);
317 } elseif (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($input)) {
318 return $this->getFileObject($input);
319 } elseif (strpos($input, ':') > 0) {
320 list($prefix, $folderIdentifier) = explode(':', $input);
321 if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($prefix)) {
322 // path or folder in a valid storageUID
323 return $this->getObjectFromCombinedIdentifier($input);
324 } elseif ($prefix == 'EXT') {
325 $input = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($input);
326 $input = \t3lib_Utility_Path::getRelativePath(PATH_site, dirname($input)) . basename($input);
327 return $this->getFileObjectFromCombinedIdentifier($input);
328 }
329 } else {
330 // only the path
331 return $this->getFileObjectFromCombinedIdentifier($input);
332 }
333 }
334
335 /**
336 * Gets an file object from an identifier [storage]:[fileId]
337 *
338 * @TODO check naming, inserted by SteffenR while working on filelist
339 * @param string $identifier
340 * @return Folder
341 */
342 public function getFolderObjectFromCombinedIdentifier($identifier) {
343 $parts = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(':', $identifier);
344 if (count($parts) === 2) {
345 $storageUid = $parts[0];
346 $folderIdentifier = $parts[1];
347 } else {
348 // We only got a path: Go into backwards compatibility mode and
349 // use virtual Storage (uid=0)
350 $storageUid = 0;
351 $folderIdentifier = substr($parts[0], strlen(PATH_site));
352 }
353 return $this->getStorageObject($storageUid)->getFolder($folderIdentifier);
354 }
355
356 /**
357 * Gets a storage object from a combined identifier
358 *
359 * @param string $identifier An identifier of the form [storage uid]:[object identifier]
360 * @return ResourceStorage
361 */
362 public function getStorageObjectFromCombinedIdentifier($identifier) {
363 $parts = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(':', $identifier);
364 if (count($parts) === 2) {
365 $storageUid = $parts[0];
366 }
367
368 return $this->getStorageObject($storageUid);
369 }
370
371 /**
372 * Gets a file or folder object.
373 *
374 * @param string $identifier
375 *
376 * @throws \TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException
377 * @return FileInterface|Folder
378 */
379 public function getObjectFromCombinedIdentifier($identifier) {
380 list($storageId, $objectIdentifier) = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(':', $identifier);
381 $storage = $this->getStorageObject($storageId);
382 if ($storage->hasFile($objectIdentifier)) {
383 return $storage->getFile($objectIdentifier);
384 } elseif ($storage->hasFolder($objectIdentifier)) {
385 return $storage->getFolder($objectIdentifier);
386 } else {
387 throw new \TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException('Object with identifier "' . $identifier . '" does not exist in storage', 1329647780);
388 }
389 }
390
391 /**
392 * Creates a file object from an array of file data. Requires a database
393 * row to be fetched.
394 *
395 * @param array $fileData
396 * @return File
397 */
398 public function createFileObject(array $fileData) {
399 /** @var File $fileObject */
400 $fileObject = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\File', $fileData);
401 if (is_numeric($fileData['storage'])) {
402 $storageObject = $this->getStorageObject($fileData['storage']);
403 $fileObject->setStorage($storageObject);
404 }
405 return $fileObject;
406 }
407
408 /**
409 * Creates an instance of a FileReference object. The $fileReferenceData can
410 * be supplied to increase performance.
411 *
412 * @param integer $uid The uid of the file usage (sys_file_reference) to instantiate.
413 * @param array $fileReferenceData The record row from database.
414 *
415 * @throws \InvalidArgumentException
416 * @return FileReference
417 */
418 public function getFileReferenceObject($uid, array $fileReferenceData = array()) {
419 if (!is_numeric($uid)) {
420 throw new \InvalidArgumentException('uid of fileusage (sys_file_reference) has to be numeric.', 1300086584);
421 }
422 if (!$this->fileReferenceInstances[$uid]) {
423 // Fetches data in case $fileData is empty
424 if (empty($fileReferenceData)) {
425 // fetch the reference record of the current workspace
426 if (TYPO3_MODE === 'BE') {
427 $fileReferenceData = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecordWSOL('sys_file_reference', $uid);
428 } elseif (is_object($GLOBALS['TSFE'])) {
429 $fileReferenceData = $GLOBALS['TSFE']->sys_page->checkRecord('sys_file_reference', $uid);
430 } else {
431 /** @var $GLOBALS['TYPO3_DB'] \TYPO3\CMS\Core\Database\DatabaseConnection */
432 $fileReferenceData = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', 'sys_file_reference', 'uid=' . intval($uid) . ' AND deleted=0');
433 }
434 if (!is_array($fileReferenceData)) {
435 throw new \InvalidArgumentException('No fileusage (sys_file_reference) found for given UID.', 1317178794);
436 }
437 }
438 $this->fileReferenceInstances[$uid] = $this->createFileReferenceObject($fileReferenceData);
439 }
440 return $this->fileReferenceInstances[$uid];
441 }
442
443 /**
444 * Creates a file usage object from an array of fileReference data
445 * from sys_file_reference table.
446 * Requires a database row to be already fetched and present.
447 *
448 * @param array $fileReferenceData
449 * @return FileReference
450 */
451 public function createFileReferenceObject(array $fileReferenceData) {
452 /** @var FileReference $fileReferenceObject */
453 $fileReferenceObject = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\FileReference', $fileReferenceData);
454 return $fileReferenceObject;
455 }
456 }
457
458
459 ?>