[TASK] Clean up and fix unit tests for FAL
[Packages/TYPO3.CMS.git] / t3lib / file / Factory.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 * Factory class for FAL objects.
31 *
32 * NOTE: This class is part of the lowlevel FAL API and should not be used from outside the FAL package.
33 *
34 * @author Andreas Wolf <andreas.wolf@ikt-werk.de>
35 * @package TYPO3
36 * @subpackage t3lib
37 */
38
39 // TODO implement constructor-level caching
40 class t3lib_file_Factory implements t3lib_Singleton {
41
42 /**
43 * Gets a singleton instance of this class.
44 *
45 * @return t3lib_file_Factory
46 */
47 public static function getInstance() {
48 return t3lib_div::makeInstance('t3lib_file_Factory');
49 }
50
51 /**
52 * @var t3lib_file_Storage[]
53 */
54 protected $storageInstances = array();
55
56 /**
57 * @var t3lib_file_AbstractCollection[]
58 */
59 protected $collectionInstances = array();
60
61 /**
62 * @var t3lib_file_File[]
63 */
64 protected $fileInstances = array();
65
66 /**
67 * @var t3lib_file_FileReference[]
68 */
69 protected $fileReferenceInstances = array();
70
71 /**
72 * Creates a driver object for a specified storage object.
73 *
74 * @param string $driverIdentificationString The driver class (or identifier) to use.
75 * @param array $driverConfiguration The configuration of the storage
76 * @return t3lib_file_Driver_AbstractDriver
77 * @throws InvalidArgumentException
78 */
79 public function getDriverObject($driverIdentificationString, array $driverConfiguration) {
80 /** @var $driverRegistry t3lib_file_Driver_DriverRegistry */
81 $driverRegistry = t3lib_div::makeInstance('t3lib_file_Driver_DriverRegistry');
82 $driverClass = $driverRegistry->getDriverClass($driverIdentificationString);
83
84 $driverObject = t3lib_div::makeInstance($driverClass, $driverConfiguration);
85
86 return $driverObject;
87 }
88
89 /**
90 * Creates an instance of the storage from given UID. The $recordData can
91 * be supplied to increase performance.
92 *
93 * @param integer $uid The uid of the storage to instantiate.
94 * @param array $recordData The record row from database.
95 * @return t3lib_file_Storage
96 */
97 public function getStorageObject($uid, array $recordData = array()) {
98 if (!is_numeric($uid)) {
99 throw new InvalidArgumentException('uid of Storage has to be numeric.', 1314085991);
100 }
101
102 if (!$this->storageInstances[$uid]) {
103 $storageConfiguration = NULL;
104 $storageObject = NULL;
105
106 // If the built-in storage with UID=0 is requested:
107 if (intval($uid) === 0) {
108 $recordData = array(
109 'uid' => 0,
110 'pid' => 0,
111 'name' => 'Default Storage',
112 'description' => 'Internal storage, mounting the main TYPO3_site directory.',
113 'driver' => 'Local',
114 'processingfolder' => 'typo3temp/_processed_/', // legacy code
115 'configuration' => '',
116 'is_online' => TRUE,
117 'is_browsable' => TRUE,
118 'is_public' => TRUE,
119 'is_writable' => TRUE,
120 );
121
122 $storageConfiguration = array(
123 'basePath' => '/',
124 'pathType' => 'relative'
125 );
126
127 // If any other (real) storage is requested:
128 // Get storage data if not already supplied as argument to this function
129 } elseif (count($recordData) === 0 || $recordData['uid'] !== $uid) {
130 /** @var $storageRepository t3lib_file_Repository_StorageRepository */
131 $storageRepository = t3lib_div::makeInstance('t3lib_file_Repository_StorageRepository');
132 /** @var $storage t3lib_file_Storage */
133 $storageObject = $storageRepository->findByUid($uid);
134 }
135 if(!($storageObject instanceof t3lib_file_Storage)) {
136 $storageObject = $this->createStorageObject($recordData, $storageConfiguration);
137 }
138 $this->storageInstances[$uid] = $storageObject;
139 }
140
141 return $this->storageInstances[$uid];
142 }
143
144 /**
145 * Converts a flexform data string to a flat array with key value pairs
146 *
147 * @param string $flexFormData
148 * @return array Array with key => value pairs of the field data in the FlexForm
149 */
150 public function convertFlexFormDataToConfigurationArray($flexFormData) {
151 $configuration = array();
152 if ($flexFormData) {
153 $flexFormContents = t3lib_div::xml2array($flexFormData);
154 if (!empty($flexFormContents['data']['sDEF']['lDEF']) && is_array($flexFormContents['data']['sDEF']['lDEF'])) {
155 foreach ($flexFormContents['data']['sDEF']['lDEF'] as $key => $value) {
156 if (isset($value['vDEF'])) {
157 $configuration[$key] = $value['vDEF'];
158 }
159 }
160 }
161 }
162
163 return $configuration;
164 }
165
166
167 /**
168 * Creates an instance of the collection from given UID. The $recordData can be supplied to increase performance.
169 *
170 * @param integer $uid The uid of the collection to instantiate.
171 * @param array $recordData The record row from database.
172 * @return t3lib_file_Collection_AbstractFileCollection
173 */
174 public function getCollectionObject($uid, array $recordData = array()) {
175 if (!is_numeric($uid)) {
176 throw new InvalidArgumentException('uid of collection has to be numeric.', 1314085999);
177 }
178
179 if (!$this->collectionInstances[$uid]) {
180 // Get mount data if not already supplied as argument to this function
181 if (count($recordData) === 0 || $recordData['uid'] !== $uid) {
182 /** @var $GLOBALS['TYPO3_DB'] t3lib_DB */
183 $recordData = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow(
184 '*',
185 'sys_file_collection',
186 'uid=' . intval($uid) . ' AND deleted=0'
187 );
188
189 if (!is_array($recordData)) {
190 throw new InvalidArgumentException('No collection found for given UID.', 1314085992);
191 }
192 }
193
194 $collectionObject = $this->createCollectionObject($recordData);
195 $this->collectionInstances[$uid] = $collectionObject;
196 }
197
198 return $this->collectionInstances[$uid];
199 }
200
201 /**
202 * Creates a collection object.
203 *
204 * @param array $collectionData The database row of the sys_file_collection record.
205 * @return t3lib_file_Collection_AbstractFileCollection
206 */
207 public function createCollectionObject(array $collectionData) {
208
209 switch ($collectionData['type']) {
210 case 'static':
211 $collection = t3lib_file_Collection_StaticFileCollection::create($collectionData);
212 break;
213 case 'folder':
214 $collection = t3lib_file_Collection_FolderBasedFileCollection::create($collectionData);
215 break;
216 default:
217 $collection = NULL;
218 }
219
220 return $collection;
221 }
222
223 /**
224 * Creates a storage object from a storage database row.
225 *
226 * @param array $storageRecord
227 * @param array $storageConfiguration Storage configuration (if given, this won't be extracted from the FlexForm value but the supplied array used instead)
228 * @return t3lib_file_Storage
229 */
230 public function createStorageObject(array $storageRecord, array $storageConfiguration=NULL) {
231 $className = 't3lib_file_Storage';
232
233 if (!$storageConfiguration) {
234 $storageConfiguration = $this->convertFlexFormDataToConfigurationArray($storageRecord['configuration']);
235 }
236
237 $driverType = $storageRecord['driver'];
238 $driverObject = $this->getDriverObject($driverType, $storageConfiguration);
239
240 /** @var $storage t3lib_file_Storage */
241 $storage = t3lib_div::makeInstance($className, $driverObject, $storageRecord);
242
243 // TODO handle publisher
244
245 return $storage;
246 }
247
248 /**
249 * Creates a folder to directly access (a part of) a storage.
250 *
251 * @param t3lib_file_Storage $storage The storage the folder belongs to
252 * @param string $identifier The path to the folder. Might also be a simple unique string, depending on the storage driver.
253 * @param string $name The name of the folder (e.g. the folder name)
254 * @return t3lib_file_Folder
255 */
256 public function createFolderObject(t3lib_file_Storage $storage, $identifier, $name) {
257 return t3lib_div::makeInstance('t3lib_file_Folder', $storage, $identifier, $name);
258 }
259
260 protected function createPublisherFromConfiguration(array $configuration) {
261 $publishingTarget = $this->getStorageObject($configuration['publisherConfiguration']['publishingTarget']);
262 $publisher = t3lib_div::makeInstance($configuration['publisher'], $publishingTarget, $configuration['publisherConfiguration']);
263 return $publisher;
264 }
265
266 /**
267 * Creates an instance of the file given UID. The $fileData can be supplied
268 * to increase performance.
269 *
270 * @param integer $uid The uid of the file to instantiate.
271 * @param array $fileData The record row from database.
272 * @return t3lib_file_File
273 */
274 public function getFileObject($uid, array $fileData = array()) {
275 if (!is_numeric($uid)) {
276 throw new InvalidArgumentException('uid of file has to be numeric.', 1300096564);
277 }
278
279 if (!$this->fileInstances[$uid]) {
280 // Fetches data in case $fileData is empty
281 if (empty($fileData)) {
282 /** @var $GLOBALS['TYPO3_DB'] t3lib_DB */
283 $fileData = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', 'sys_file', 'uid=' . intval($uid) . ' AND deleted=0');
284 if (!is_array($fileData)) {
285 throw new InvalidArgumentException('No file found for given UID.', 1317178604);
286 }
287 }
288
289 $this->fileInstances[$uid] = $this->createFileObject($fileData);
290 }
291
292 return $this->fileInstances[$uid];
293 }
294
295 /**
296 * Gets an file object from an identifier [storage]:[fileId]
297 *
298 * @param string $identifier
299 * @return t3lib_file_File
300 */
301 public function getFileObjectFromCombinedIdentifier($identifier) {
302 $parts = t3lib_div::trimExplode(':', $identifier);
303
304 if (count($parts) === 2) {
305 $storageUid = $parts[0];
306 $fileIdentifier = $parts[1];
307 } else {
308 // We only got a path: Go into backwards compatibility mode and
309 // use virtual Storage (uid=0)
310 $storageUid = 0;
311 $fileIdentifier = $parts[0];
312 }
313
314 return $this->getStorageObject($storageUid)->getFile($fileIdentifier);
315 }
316
317 /**
318 * Bulk function, can be used for anything to get a file or folder
319 *
320 * 1. It's a UID
321 * 2. It's a combined identifier
322 * 3. It's just a path/filename (coming from the oldstyle/backwards compatibility)
323 *
324 * Files, previously laid on fileadmin/ or something, will be "mapped" to the storage the file is
325 * in now. Files like typo3temp/ or typo3conf/ will be moved to the first writable storage
326 * in its processing folder
327 *
328 * $input could be
329 * - "2:myfolder/myfile.jpg" (combined identifier)
330 * - "23" (file UID)
331 * - "uploads/myfile.png" (backwards-compatibility, storage "0")
332 * - "file:23"
333 * @param string $input
334 * @return t3lib_file_FileInterface|t3lib_file_Folder
335 */
336 public function retrieveFileOrFolderObject($input) {
337 // Easy function to deal with that, could be dropped in the future
338 // if we know where to use this function
339 if (t3lib_div::isFirstPartOfStr($input, 'file:')) {
340 $input = substr($input, 5);
341 return $this->retrieveFileOrFolderObject($input);
342 } elseif (t3lib_utility_Math::canBeInterpretedAsInteger($input)) {
343 return $this->getFileObject($input);
344 } elseif (strpos($input, ':') > 0) {
345 list($prefix, $folderIdentifier) = explode(':', $input);
346 if (t3lib_utility_Math::canBeInterpretedAsInteger($prefix)) {
347 // path or folder in a valid storageUID
348 return $this->getObjectFromCombinedIdentifier($input);
349
350 } elseif ($prefix == 'EXT') {
351 $input = t3lib_div::getFileAbsFileName($input);
352 $input = t3lib_Utility_Path::getRelativePath(PATH_site, dirname($input)).basename($input);
353 return $this->getFileObjectFromCombinedIdentifier($input);
354 }
355 } else {
356 // only the path
357 return $this->getFileObjectFromCombinedIdentifier($input);
358 }
359 }
360
361
362 /**
363 * Gets an file object from an identifier [storage]:[fileId]
364 *
365 * @TODO check naming, inserted by SteffenR while working on filelist
366 * @param string $identifier
367 * @return t3lib_file_Folder
368 */
369 public function getFolderObjectFromCombinedIdentifier($identifier) {
370 $parts = t3lib_div::trimExplode(':', $identifier);
371
372 if (count($parts) === 2) {
373 $storageUid = $parts[0];
374 $folderIdentifier = $parts[1];
375 } else {
376 // We only got a path: Go into backwards compatibility mode and
377 // use virtual Storage (uid=0)
378 $storageUid = 0;
379 $folderIdentifier = substr($parts[0], strlen(PATH_site));
380 }
381
382 return $this->getStorageObject($storageUid)->getFolder($folderIdentifier);
383 }
384
385 /**
386 * Gets a file or folder object.
387 *
388 * @param string $identifier
389 * @return t3lib_file_FileInterface|t3lib_file_Folder
390 */
391 public function getObjectFromCombinedIdentifier($identifier) {
392 list($storageId, $objectIdentifier) = t3lib_div::trimExplode(':', $identifier);
393 $storage = $this->getStorageObject($storageId);
394
395 if ($storage->hasFile($objectIdentifier)) {
396 return $storage->getFile($objectIdentifier);
397 } elseif ($storage->hasFolder($objectIdentifier)) {
398 return $storage->getFolder($objectIdentifier);
399 } else {
400 throw new RuntimeException(
401 'Object with identifier "' . $identifier . '" does not exist in storage',
402 1329647780
403 );
404 }
405 }
406
407 /**
408 * Creates a file object from an array of file data. Requires a database
409 * row to be fetched.
410 *
411 * @param array $fileData
412 * @return t3lib_file_File
413 */
414 public function createFileObject(array $fileData) {
415 /** @var t3lib_file_File $fileObject */
416 $fileObject = t3lib_div::makeInstance('t3lib_file_File', $fileData);
417
418 if (is_numeric($fileData['storage'])) {
419 $storageObject = $this->getStorageObject($fileData['storage']);
420 $fileObject->setStorage($storageObject);
421 }
422
423 return $fileObject;
424 }
425
426 /**
427 * Creates an instance of a FileReference object. The $fileReferenceData can
428 * be supplied to increase performance.
429 *
430 * @param integer $uid The uid of the file usage (sys_file_reference) to instantiate.
431 * @param array $fileReferenceData The record row from database.
432 * @return t3lib_file_FileReference
433 */
434 public function getFileReferenceObject($uid, array $fileReferenceData = array()) {
435 if (!is_numeric($uid)) {
436 throw new InvalidArgumentException('uid of fileusage (sys_file_reference) has to be numeric.', 1300086584);
437 }
438
439
440 if (!$this->fileReferenceInstances[$uid]) {
441 // Fetches data in case $fileData is empty
442 if (empty($fileReferenceData)) {
443
444 // fetch the reference record of the current workspace
445 if (TYPO3_MODE === 'BE') {
446 $fileReferenceData = t3lib_BEfunc::getRecordWSOL('sys_file_reference', $uid);
447 } elseif (is_object($GLOBALS['TSFE'])) {
448 $fileReferenceData = $GLOBALS['TSFE']->sys_page->checkRecord('sys_file_reference', $uid);
449 } else {
450 /** @var $GLOBALS['TYPO3_DB'] t3lib_DB */
451 $fileReferenceData = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow(
452 '*',
453 'sys_file_reference',
454 'uid=' . intval($uid) . ' AND deleted=0'
455 );
456 }
457
458 if (!is_array($fileReferenceData)) {
459 throw new InvalidArgumentException('No fileusage (sys_file_reference) found for given UID.', 1317178794);
460 }
461 }
462
463 $this->fileReferenceInstances[$uid] = $this->createFileReferenceObject($fileReferenceData);
464 }
465
466 return $this->fileReferenceInstances[$uid];
467 }
468
469 /**
470 * Creates a file usage object from an array of fileReference data
471 * from sys_file_reference table.
472 * Requires a database row to be already fetched and present.
473 *
474 * @param array $fileReferenceData
475 * @return t3lib_file_FileReference
476 */
477 public function createFileReferenceObject(array $fileReferenceData) {
478 /** @var t3lib_file_FileReference $fileReferenceObject */
479 $fileReferenceObject = t3lib_div::makeInstance('t3lib_file_FileReference', $fileReferenceData);
480 return $fileReferenceObject;
481 }
482
483 /**
484 * Generates a new object of the type t3lib_file_ProcessedFile
485 * additionally checks if this processed file already exists in the DB
486 *
487 * @param t3lib_file_FileInterface $originalFileObject
488 * @param string $context The context the file is processed in
489 * @param array $configuration The processing configuration
490 * @return t3lib_file_ProcessedFile
491 */
492 public function getProcessedFileObject(t3lib_file_FileInterface $originalFileObject, $context, array $configuration) {
493 /** @var t3lib_file_ProcessedFile $processedFileObject */
494 $processedFileObject = t3lib_div::makeInstance(
495 't3lib_file_ProcessedFile',
496 $originalFileObject,
497 $context,
498 $configuration);
499
500 /* @var t3lib_file_Repository_ProcessedFileRepository $repository */
501 $repository = t3lib_div::makeInstance('t3lib_file_Repository_ProcessedFileRepository');
502
503 // Check if this file already exists in the DB
504 $repository->populateDataOfProcessedFileObject($processedFileObject);
505
506 return $processedFileObject;
507 }
508 }
509
510 ?>