062c573e470b18cfdc6a793f05d824a5fe8984fc
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Resource / File.php
1 <?php
2 namespace TYPO3\CMS\Core\Resource;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 2011-2013 Ingo Renner <ingo@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 text file 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
30 use TYPO3\CMS\Core\Utility\GeneralUtility;
31
32 /**
33 * File representation in the file abstraction layer.
34 *
35 * @author Andreas Wolf <andreas.wolf@ikt-werk.de>
36 */
37 class File extends AbstractFile {
38
39 /**
40 * File indexing status. True, if the file is indexed in the database;
41 * NULL is the default value, this means that the index status is unknown
42 *
43 * @var boolean|NULL
44 */
45 protected $indexed = NULL;
46
47 /**
48 * Tells whether to index a file or not.
49 * If yes, the file will be persisted into sys_file.
50 *
51 * @var boolean
52 */
53 protected $indexable = TRUE;
54
55 /**
56 * @var array
57 */
58 protected $metaDataProperties = array();
59
60 /**
61 * Set to TRUE while this file is being indexed - used to prevent some endless loops
62 *
63 * @var boolean
64 */
65 protected $indexingInProgress = FALSE;
66
67 /**
68 * Contains the names of all properties that have been update since the
69 * instantiation of this object
70 *
71 * @var array
72 */
73 protected $updatedProperties = array();
74
75 /**
76 * @var \TYPO3\CMS\Core\Resource\Service\IndexerService
77 */
78 protected $indexerService = NULL;
79
80 /**
81 * Constructor for a file object. Should normally not be used directly, use
82 * the corresponding factory methods instead.
83 *
84 * @param array $fileData
85 * @param ResourceStorage $storage
86 */
87 public function __construct(array $fileData, ResourceStorage $storage) {
88 $this->identifier = $fileData['identifier'];
89 $this->name = $fileData['name'];
90 $this->properties = $fileData;
91 $this->storage = $storage;
92
93 if (isset($fileData['uid']) && intval($fileData['uid']) > 0) {
94 $this->indexed = TRUE;
95 $this->loadMetaData();
96 }
97 }
98
99 /*******************************
100 * VARIOUS FILE PROPERTY GETTERS
101 *******************************/
102 /**
103 * Returns a property value
104 *
105 * @param string $key
106 * @return mixed Property value
107 */
108 public function getProperty($key) {
109 if ($this->indexed === NULL) {
110 $this->loadIndexRecord();
111 }
112 if (parent::hasProperty($key)) {
113 return parent::getProperty($key);
114 } else {
115 return array_key_exists($key, $this->metaDataProperties) ? $this->metaDataProperties[$key] : NULL;
116 }
117 }
118
119 /**
120 * Returns the properties of this object.
121 *
122 * @return array
123 */
124 public function getProperties() {
125 if ($this->indexed === NULL) {
126 $this->loadIndexRecord();
127 }
128 return array_merge(parent::getProperties(), array_diff_key((array)$this->metaDataProperties, parent::getProperties()));
129 }
130
131 /**
132 * Returns the MetaData
133 *
134 * @return array|null
135 * @internal
136 */
137 public function _getMetaData() {
138 return $this->metaDataProperties;
139 }
140
141 /******************
142 * CONTENTS RELATED
143 ******************/
144 /**
145 * Get the contents of this file
146 *
147 * @return string File contents
148 */
149 public function getContents() {
150 return $this->getStorage()->getFileContents($this);
151 }
152
153 /**
154 * Gets SHA1 hash.
155 *
156 * @return string
157 */
158 public function getSha1() {
159 if (empty($this->properties['sha1'])) {
160 $this->properties['sha1'] = parent::getSha1();
161 }
162 return $this->properties['sha1'];
163 }
164
165 /**
166 * Replace the current file contents with the given string
167 *
168 * @param string $contents The contents to write to the file.
169 * @return File The file object (allows chaining).
170 */
171 public function setContents($contents) {
172 $this->getStorage()->setFileContents($this, $contents);
173 return $this;
174 }
175
176 /***********************
177 * INDEX RELATED METHODS
178 ***********************/
179 /**
180 * Returns TRUE if this file is indexed
181 *
182 * @return boolean|NULL
183 */
184 public function isIndexed() {
185 if ($this->indexed === NULL && !$this->indexingInProgress) {
186 $this->loadIndexRecord();
187 }
188 return $this->indexed;
189 }
190
191 /**
192 * @param bool $indexIfNotIndexed
193 *
194 * @throws \RuntimeException
195 * @return void
196 */
197 protected function loadIndexRecord($indexIfNotIndexed = TRUE) {
198 if ($this->indexed !== NULL || !$this->indexable || $this->indexingInProgress) {
199 return;
200 }
201 $this->indexingInProgress = TRUE;
202
203 $indexRecord = $this->getFileIndexRepository()->findOneByCombinedIdentifier($this->getCombinedIdentifier());
204 if ($indexRecord === FALSE && $indexIfNotIndexed) {
205 $this->getIndexerService()->updateIndexEntry($this);
206 $this->updatedProperties = array();
207 } elseif ($indexRecord !== FALSE) {
208 $this->mergeIndexRecord($indexRecord);
209 $this->indexed = TRUE;
210 $this->loadMetaData();
211 } else {
212 throw new \RuntimeException('Could not load index record for "' . $this->getIdentifier() . '"', 1321288316);
213 }
214 $this->indexingInProgress = FALSE;
215 }
216
217 /**
218 * Loads MetaData from Repository
219 */
220 protected function loadMetaData() {
221 $this->metaDataProperties = $this->getMetaDataRepository()->findByFile($this);
222 }
223
224 /**
225 * Merges the contents of this file's index record into the file properties.
226 *
227 * @param array $recordData The index record as fetched from the database
228 *
229 * @throws \InvalidArgumentException
230 * @return void
231 */
232 protected function mergeIndexRecord(array $recordData) {
233 if ($this->properties['uid'] != 0) {
234 throw new \InvalidArgumentException('uid property is already set. Cannot merge index record.', 1321023156);
235 }
236 $this->properties = array_merge($recordData, $this->properties);
237 }
238
239 /**
240 * Updates the properties of this file, e.g. after re-indexing or moving it.
241 * By default, only properties that exist as a key in the $properties array
242 * are overwritten. If you want to explicitly unset a property, set the
243 * corresponding key to NULL in the array.
244 *
245 * NOTE: This method should not be called from outside the File Abstraction Layer (FAL)!
246 *
247 * @param array $properties
248 * @return void
249 * @internal
250 */
251 public function updateProperties(array $properties) {
252 // Setting identifier and name to update values; we have to do this
253 // here because we might need a new identifier when loading
254 // (and thus possibly indexing) a file.
255 if (isset($properties['identifier'])) {
256 $this->identifier = $properties['identifier'];
257 }
258 if (isset($properties['name'])) {
259 $this->name = $properties['name'];
260 }
261 if ($this->indexed === NULL && !isset($properties['uid'])) {
262 $this->loadIndexRecord();
263 }
264 if ($this->properties['uid'] != 0 && isset($properties['uid'])) {
265 unset($properties['uid']);
266 }
267 foreach ($properties as $key => $value) {
268 if ($this->properties[$key] !== $value) {
269 if (!in_array($key, $this->updatedProperties)) {
270 $this->updatedProperties[] = $key;
271 }
272 // TODO check if we should completely remove properties that
273 // are set to NULL
274 $this->properties[$key] = $value;
275 }
276 }
277 // Updating indexing status
278 if (isset($properties['uid']) && intval($properties['uid']) > 0) {
279 $this->indexed = TRUE;
280 $this->loadMetaData();
281 }
282 if (array_key_exists('storage', $properties) && in_array('storage', $this->updatedProperties)) {
283 $this->storage = ResourceFactory::getInstance()->getStorageObject($properties['storage']);
284 }
285 }
286
287 /**
288 * Returns the names of all properties that have been updated in this record
289 *
290 * @return array
291 */
292 public function getUpdatedProperties() {
293 return $this->updatedProperties;
294 }
295
296 /****************************************
297 * STORAGE AND MANAGEMENT RELATED METHODS
298 ****************************************/
299 /**
300 * Check if a file operation (= action) is allowed for this file
301 *
302 * @param string $action, can be read, write, delete
303 * @return boolean
304 */
305 public function checkActionPermission($action) {
306 return $this->getStorage()->checkFileActionPermission($action, $this);
307 }
308
309 /*****************
310 * SPECIAL METHODS
311 *****************/
312 /**
313 * Creates a MD5 hash checksum based on the combined identifier of the file,
314 * the files' mimetype and the systems' encryption key.
315 * used to generate a thumbnail, and this hash is checked if valid
316 *
317 * @todo maybe \TYPO3\CMS\Core\Utility\GeneralUtility::hmac() could be used?
318 * @return string the MD5 hash
319 */
320 public function calculateChecksum() {
321 return md5($this->getCombinedIdentifier() . '|' . $this->getMimeType() . '|' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']);
322 }
323
324 /**
325 * Returns a modified version of the file.
326 *
327 * @param string $taskType The task type of this processing
328 * @param array $configuration the processing configuration, see manual for that
329 * @return ProcessedFile The processed file
330 */
331 public function process($taskType, array $configuration) {
332 return $this->getStorage()->processFile($this, $taskType, $configuration);
333 }
334
335 /**
336 * Returns an array representation of the file.
337 * (This is used by the generic listing module vidi when displaying file records.)
338 *
339 * @return array Array of main data of the file. Don't rely on all data to be present here, it's just a selection of the most relevant information.
340 */
341 public function toArray() {
342 $array = array(
343 'id' => $this->getCombinedIdentifier(),
344 'name' => $this->getName(),
345 'extension' => $this->getExtension(),
346 'type' => $this->getType(),
347 'mimetype' => $this->getMimeType(),
348 'size' => $this->getSize(),
349 'url' => $this->getPublicUrl(),
350 'indexed' => $this->indexed,
351 'uid' => $this->getUid(),
352 'permissions' => array(
353 'read' => $this->checkActionPermission('read'),
354 'write' => $this->checkActionPermission('write'),
355 'delete' => $this->checkActionPermission('delete')
356 ),
357 'checksum' => $this->calculateChecksum()
358 );
359 foreach ($this->properties as $key => $value) {
360 $array[$key] = $value;
361 }
362 $stat = $this->getStorage()->getFileInfo($this);
363 foreach ($stat as $key => $value) {
364 $array[$key] = $value;
365 }
366 return $array;
367 }
368
369 /**
370 * @return boolean
371 */
372 public function isIndexable() {
373 return $this->indexable;
374 }
375
376 /**
377 * @param boolean $indexable
378 */
379 public function setIndexable($indexable) {
380 $this->indexable = $indexable;
381 }
382
383 /**
384 * @return boolean
385 */
386 public function isMissing() {
387 return (bool) $this->getProperty('missing');
388 }
389
390 /**
391 * @param boolean $missing
392 */
393 public function setMissing($missing) {
394 $this->updateProperties(array('missing' => $missing ? 1 : 0));
395 }
396
397 /**
398 * Returns a publicly accessible URL for this file
399 * When file is marked as missing or deleted no url is returned
400 *
401 * WARNING: Access to the file may be restricted by further means, e.g. some
402 * web-based authentication. You have to take care of this yourself.
403 *
404 * @param bool $relativeToCurrentScript Determines whether the URL returned should be relative to the current script, in case it is relative at all (only for the LocalDriver)
405 *
406 * @return string
407 */
408 public function getPublicUrl($relativeToCurrentScript = FALSE) {
409 if ($this->isMissing() || $this->deleted) {
410 return FALSE;
411 } else {
412 return $this->getStorage()->getPublicUrl($this, $relativeToCurrentScript);
413 }
414 }
415
416 /**
417 * @return \TYPO3\CMS\Core\Resource\Index\MetaDataRepository
418 */
419 protected function getMetaDataRepository() {
420 return GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\Index\\MetaDataRepository');
421 }
422
423 /**
424 * @return \TYPO3\CMS\Core\Resource\Index\FileIndexRepository
425 */
426 protected function getFileIndexRepository() {
427 return GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\Index\\FileIndexRepository');
428 }
429
430 /**
431 * Internal function to retrieve the indexer service,
432 * if it does not exist, an instance will be created
433 *
434 * @return Index\Indexer
435 */
436 protected function getIndexerService() {
437 if ($this->indexerService === NULL) {
438 $this->indexerService = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\Index\\Indexer', $this->storage);
439 }
440 return $this->indexerService;
441 }
442
443 /**
444 * @param boolean $indexingState
445 * @internal Only for usage in Indexer
446 */
447 public function setIndexingInProgess($indexingState) {
448 $this->indexingInProgress = (boolean)$indexingState;
449 }
450
451 /**
452 * @param $key
453 * @internal Only for use in Repositories and indexer
454 * @return mixed
455 */
456 public function _getPropertyRaw($key) {
457 return parent::getProperty($key);
458 }
459 }