[BUGFIX] Fix the display of references in filelist
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Utility / File / ExtendedFileUtility.php
1 <?php
2 namespace TYPO3\CMS\Core\Utility\File;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
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 /**
30 * Extending class to class t3lib_basicFileFunctions
31 *
32 * Revised for TYPO3 3.6 May/2004 by Kasper Skårhøj
33 *
34 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
35 */
36 /**
37 * Contains functions for performing file operations like copying, pasting, uploading, moving, deleting etc. through the TCE
38 * Extending class to class t3lib_basicFileFunctions.
39 *
40 * see basicFileFunctions
41 * see document "TYPO3 Core API" for syntax
42 *
43 * This class contains functions primarily used by tce_file.php (TYPO3 Core Engine for file manipulation)
44 * Functions include copying, moving, deleting, uploading and so on...
45 *
46 * Important internal variables:
47 *
48 * $filemounts (see basicFileFunctions)
49 * $f_ext (see basicFileFunctions)
50 * ... All fileoperations must be within the filemount-paths. Further the fileextension MUST validate TRUE with the f_ext array
51 *
52 * The unzip-function allows unzip only if the destination path has it's f_ext[]['allow'] set to '*'!!
53 * You are allowed to copy/move folders within the same 'space' (web/ftp).
54 * You are allowed to copy/move folders between spaces (web/ftp) IF the destination has it's f_ext[]['allow'] set to '*'!
55 *
56 * Advice:
57 * You should always exclude php-files from the webspace. This will keep people from uploading, copy/moving and renaming files to become executable php scripts.
58 * You should never mount a ftp_space 'below' the webspace so that it reaches into the webspace. This is because if somebody unzips a zip-file in the ftp-space so that it reaches out into the webspace this will be a violation of the safety
59 * For example this is a bad idea: you have an ftp-space that is '/www/' and a web-space that is '/www/htdocs/'
60 *
61 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
62 */
63 class ExtendedFileUtility extends \TYPO3\CMS\Core\Utility\File\BasicFileUtility {
64
65 // External static variables:
66 // Notice; some of these are overridden in the start() method with values from $GLOBALS['TYPO3_CONF_VARS']['BE']
67 // Path to unzip-program (with trailing '/')
68 /**
69 * @todo Define visibility
70 */
71 public $unzipPath = '';
72
73 // If set, the uploaded files will overwrite existing files.
74 /**
75 * @todo Define visibility
76 */
77 public $dontCheckForUnique = 0;
78
79 // This array is self-explaining (look in the class below).
80 // It grants access to the functions. This could be set from outside in order to enabled functions to users.
81 // See also the function init_actionPerms() which takes input directly from the user-record
82 /**
83 * @todo Define visibility
84 */
85 public $actionPerms = array(
86 'deleteFile' => 0,
87 // Deleting files physically
88 'deleteFolder' => 0,
89 // Deleting folders physically
90 'deleteFolderRecursively' => 0,
91 // normally folders are deleted by the PHP-function rmdir(), but with this option a user deletes with 'rm -Rf ....' which is pretty wild!
92 'moveFile' => 0,
93 'moveFolder' => 0,
94 'copyFile' => 0,
95 'copyFolder' => 0,
96 'newFolder' => 0,
97 'newFile' => 0,
98 'editFile' => 0,
99 'unzipFile' => 0,
100 'uploadFile' => 0,
101 'renameFile' => 0,
102 'renameFolder' => 0
103 );
104
105 // This is regarded to be the recycler folder
106 /**
107 * @todo Define visibility
108 */
109 public $recyclerFN = '_recycler_';
110
111 /**
112 * Whether to use recycler (0 = no, 1 = if available, 2 = always)
113 *
114 * @var integer
115 * @deprecated since TYPO3 6.0
116 * @todo Define visibility
117 */
118 public $useRecycler = 1;
119
120 // Internal, dynamic
121 // Will contain map between upload ID and the final filename
122 /**
123 * @todo Define visibility
124 */
125 public $internalUploadMap = array();
126
127 /**
128 * @todo Define visibility
129 */
130 public $lastError = '';
131
132 /**
133 * @var array
134 */
135 protected $fileCmdMap;
136
137 /**
138 * The File Factory
139 *
140 * @var \TYPO3\CMS\Core\Resource\ResourceFactory
141 */
142 protected $fileFactory;
143
144 /**
145 * Initialization of the class
146 *
147 * @param array $fileCmds Array with the commands to execute. See "TYPO3 Core API" document
148 * @return void
149 * @todo Define visibility
150 */
151 public function start($fileCmds) {
152 $unzipPath = trim($GLOBALS['TYPO3_CONF_VARS']['BE']['unzip_path']);
153 if (substr($unzipPath, -1) !== '/' && is_dir($unzipPath)) {
154 // Make sure the path ends with a slash
155 $unzipPath .= '/';
156 }
157 $this->unzipPath = $unzipPath;
158 // Initialize Object Factory
159 $this->fileFactory = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance();
160 // Initializing file processing commands:
161 $this->fileCmdMap = $fileCmds;
162 }
163
164 /**
165 * Sets up permission to perform file/directory operations.
166 * See below or the be_user-table for the significance of the various bits in $setup.
167 *
168 * @param integer $setup File permission integer from BE_USER OR'ed with permissions of back-end groups this user is a member of
169 * @return void
170 * @todo Define visibility
171 */
172 public function init_actionPerms($setup) {
173 // Files: Upload,Copy,Move,Delete,Rename
174 if (($setup & 1) == 1) {
175 $this->actionPerms['uploadFile'] = 1;
176 $this->actionPerms['copyFile'] = 1;
177 $this->actionPerms['moveFile'] = 1;
178 $this->actionPerms['deleteFile'] = 1;
179 $this->actionPerms['renameFile'] = 1;
180 $this->actionPerms['editFile'] = 1;
181 $this->actionPerms['newFile'] = 1;
182 }
183 // Files: Unzip
184 if (($setup & 2) == 2) {
185 $this->actionPerms['unzipFile'] = 1;
186 }
187 // Directory: Move,Delete,Rename,New
188 if (($setup & 4) == 4) {
189 $this->actionPerms['moveFolder'] = 1;
190 $this->actionPerms['deleteFolder'] = 1;
191 $this->actionPerms['renameFolder'] = 1;
192 $this->actionPerms['newFolder'] = 1;
193 }
194 // Directory: Copy
195 if (($setup & 8) == 8) {
196 $this->actionPerms['copyFolder'] = 1;
197 }
198 // Directory: Delete recursively (rm -Rf)
199 if (($setup & 16) == 16) {
200 $this->actionPerms['deleteFolderRecursively'] = 1;
201 }
202 }
203
204 /**
205 * Processing the command array in $this->fileCmdMap
206 *
207 * @return mixed FALSE, if the file functions were not initialized
208 * @todo Define visibility
209 */
210 public function processData() {
211 $result = array();
212 if (!$this->isInit) {
213 return FALSE;
214 }
215 if (is_array($this->fileCmdMap)) {
216 // Check if there were uploads expected, but no one made
217 if ($this->fileCmdMap['upload']) {
218 $uploads = $this->fileCmdMap['upload'];
219 foreach ($uploads as $upload) {
220 if (!$_FILES[('upload_' . $upload['data'])]['name']) {
221 unset($this->fileCmdMap['upload'][$upload['data']]);
222 }
223 }
224 if (count($this->fileCmdMap['upload']) == 0) {
225 $this->writelog(1, 1, 108, 'No file was uploaded!', '');
226 }
227 }
228 // Traverse each set of actions
229 foreach ($this->fileCmdMap as $action => $actionData) {
230 // Traverse all action data. More than one file might be affected at the same time.
231 if (is_array($actionData)) {
232 $result[$action] = array();
233 foreach ($actionData as $cmdArr) {
234 // Clear file stats
235 clearstatcache();
236 // Branch out based on command:
237 switch ($action) {
238 case 'delete':
239 $result[$action][] = $this->func_delete($cmdArr);
240 break;
241 case 'copy':
242 $result[$action][] = $this->func_copy($cmdArr);
243 break;
244 case 'move':
245 $result[$action][] = $this->func_move($cmdArr);
246 break;
247 case 'rename':
248 $result[$action][] = $this->func_rename($cmdArr);
249 break;
250 case 'newfolder':
251 $result[$action][] = $this->func_newfolder($cmdArr);
252 break;
253 case 'newfile':
254 $result[$action][] = $this->func_newfile($cmdArr);
255 break;
256 case 'editfile':
257 $result[$action][] = $this->func_edit($cmdArr);
258 break;
259 case 'upload':
260 $result[$action][] = $this->func_upload($cmdArr);
261 break;
262 case 'unzip':
263 $result[$action][] = $this->func_unzip($cmdArr);
264 break;
265 }
266 // Hook for post-processing the action
267 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_extfilefunc.php']['processData'])) {
268 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_extfilefunc.php']['processData'] as $classRef) {
269 $hookObject = \TYPO3\CMS\Core\Utility\GeneralUtility::getUserObj($classRef);
270 if (!$hookObject instanceof \TYPO3\CMS\Core\Utility\File\ExtendedFileUtilityProcessDataHookInterface) {
271 throw new \UnexpectedValueException('$hookObject must implement interface TYPO3\\CMS\\Core\\Utility\\File\\ExtendedFileUtilityProcessDataHookInterface', 1279719168);
272 }
273 $hookObject->processData_postProcessAction($action, $cmdArr, $result[$action], $this);
274 }
275 }
276 }
277 }
278 }
279 }
280 return $result;
281 }
282
283 /**
284 * Adds log error messages from the operations of this script instance to the FlashMessageQueue
285 *
286 * @param string $redirect Redirect URL (for creating link in message)
287 * @return void
288 * @todo Define visibility
289 */
290 public function printLogErrorMessages($redirect = '') {
291 $this->getErrorMessages();
292 }
293
294 /**
295 * Adds log error messages from the previous file operations of this script instance
296 * to the FlashMessageQueue
297 *
298 * @return void
299 * @todo Define visibility
300 */
301 public function getErrorMessages() {
302 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_log', 'type = 2 AND userid = ' . intval($GLOBALS['BE_USER']->user['uid']) . ' AND tstamp=' . intval($GLOBALS['EXEC_TIME']) . ' AND error<>0');
303 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
304 $logData = unserialize($row['log_data']);
305 $msg = $row['error'] . ': ' . sprintf($row['details'], $logData[0], $logData[1], $logData[2], $logData[3], $logData[4]);
306 $flashMessage = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessage', $msg, '', \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR, TRUE);
307 \TYPO3\CMS\Core\Messaging\FlashMessageQueue::addMessage($flashMessage);
308 }
309 $GLOBALS['TYPO3_DB']->sql_free_result($res);
310 }
311
312 /**
313 * Goes back in the path and checks in each directory if a folder named $this->recyclerFN (usually '_recycler_') is present.
314 * If a folder in the tree happens to be a _recycler_-folder (which means that we're deleting something inside a _recycler_-folder) this is ignored
315 *
316 * @param string $theFile Takes a valid Path ($theFile)
317 * @return string Returns the path (without trailing slash) of the closest recycle-folder if found. Else FALSE.
318 * @todo To be put in Storage with a better concept
319 * @todo Define visibility
320 * @deprecated since TYPO3 6.0, use \TYPO3\CMS\Core\Resource\ResourceStorage method instead
321 */
322 public function findRecycler($theFile) {
323 \TYPO3\CMS\Core\Utility\GeneralUtility::logDeprecatedFunction();
324 if ($this->isPathValid($theFile)) {
325 $theFile = $this->cleanDirectoryName($theFile);
326 $fI = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($theFile);
327 $c = 0;
328 // !!! Method has been put in the storage, can be saftely removed
329 $rDir = $fI['path'] . $this->recyclerFN;
330 while ($this->checkPathAgainstMounts($fI['path']) && $c < 20) {
331 if (@is_dir($rDir) && $this->recyclerFN != $fI['file']) {
332 return $rDir;
333 }
334 $theFile = $fI['path'];
335 $theFile = $this->cleanDirectoryName($theFile);
336 $fI = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($theFile);
337 $c++;
338 }
339 }
340 }
341
342 /**
343 * Logging file operations
344 *
345 * @param integer $action The action number. See the functions in the class for a hint. Eg. edit is '9', upload is '1' ...
346 * @param integer $error The severity: 0 = message, 1 = error, 2 = System Error, 3 = security notice (admin)
347 * @param integer $details_nr This number is unique for every combination of $type and $action. This is the error-message number, which can later be used to translate error messages.
348 * @param string $details This is the default, raw error message in english
349 * @param array $data Array with special information that may go into $details by "%s" marks / sprintf() when the log is shown
350 * @return void
351 * @see class.t3lib_beuserauth.php
352 * @todo Define visibility
353 */
354 public function writeLog($action, $error, $details_nr, $details, $data) {
355 // Type value for tce_file.php
356 $type = 2;
357 if (is_object($GLOBALS['BE_USER'])) {
358 $GLOBALS['BE_USER']->writelog($type, $action, $error, $details_nr, $details, $data);
359 }
360 $this->lastError = vsprintf($details, $data);
361 }
362
363 /*************************************
364 *
365 * File operation functions
366 *
367 **************************************/
368 /**
369 * Deleting files and folders (action=4)
370 *
371 * @param array $cmds $cmds['data'] is the file/folder to delete
372 * @return boolean Returns TRUE upon success
373 * @todo Define visibility
374 */
375 public function func_delete($cmds) {
376 $result = FALSE;
377 if (!$this->isInit) {
378 return $result;
379 }
380 // Example indentifier for $cmds['data'] => "4:mypath/tomyfolder/myfile.jpg"
381 // for backwards compatibility: the combined file identifier was the path+filename
382 $fileObject = $this->getFileObject($cmds['data']);
383 // @todo implement the recycler feature which has been removed from the original implementation
384 // checks to delete the file
385 if ($fileObject instanceof \TYPO3\CMS\Core\Resource\File) {
386 $refIndexRecords = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
387 '*',
388 'sys_refindex',
389 'deleted=0 AND ref_table="sys_file" AND ref_uid=' . intval($fileObject->getUid())
390 );
391 // check if the file still has references
392 if (count($refIndexRecords) > 0) {
393 $shortcutContent = array();
394 foreach ($refIndexRecords as $fileReferenceRow) {
395 if ($fileReferenceRow['tablename'] === 'sys_file_reference') {
396 $row = $this->transformFileReferenceToRecordReference($fileReferenceRow);
397 $shortcutRecord = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord($row['tablename'], $row['recuid']);
398 $icon = \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIconForRecord($row['tablename'], $shortcutRecord);
399 $onClick = 'showClickmenu("' . $row['tablename'] . '", "' . $row['recuid'] . '", "1", "+info,history,edit", "|", "");return false;';
400 $shortcutContent[] = '<a href="#" oncontextmenu="' . htmlspecialchars($onClick) . '" onclick="' . htmlspecialchars($onClick) . '">' . $icon . '</a>' . htmlspecialchars((\TYPO3\CMS\Backend\Utility\BackendUtility::getRecordTitle($row['tablename'], $shortcutRecord) . ' [' . \TYPO3\CMS\Backend\Utility\BackendUtility::getRecordPath($shortcutRecord['pid'], '', 80) . ']'));
401 }
402 }
403 $out = '<p>The file cannot be deleted since it is still used at the following places:<br />' . implode('<br />', $shortcutContent) . '</p>';
404 $flashMessage = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('t3lib_flashMessage', $out, 'File not deleted', \TYPO3\CMS\Core\Messaging\FlashMessage::WARNING, TRUE);
405 \TYPO3\CMS\Core\Messaging\FlashMessageQueue::addMessage($flashMessage);
406 return;
407 } else {
408 try {
409 $result = $fileObject->delete();
410 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
411 $this->writelog(4, 1, 112, 'You are not allowed to access the file', array($fileObject->getIdentifier()));
412 } catch (\TYPO3\CMS\Core\Resource\Exception\NotInMountPointException $e) {
413 $this->writelog(4, 1, 111, 'Target was not within your mountpoints! T="%s"', array($fileObject->getIdentifier()));
414 } catch (\RuntimeException $e) {
415 $this->writelog(4, 1, 110, 'Could not delete file "%s". Write-permission problem?', array($fileObject->getIdentifier()));
416 }
417 // Log success
418 $this->writelog(4, 0, 1, 'File "%s" deleted', array($fileObject->getIdentifier()));
419 }
420 } else {
421 try {
422 /** @var $fileObject \TYPO3\CMS\Core\Resource\FolderInterface */
423 $result = $fileObject->delete(TRUE);
424 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
425 $this->writelog(4, 1, 123, 'You are not allowed to access the directory', array($fileObject->getIdentifier()));
426 } catch (\TYPO3\CMS\Core\Resource\Exception\NotInMountPointException $e) {
427 $this->writelog(4, 1, 121, 'Target was not within your mountpoints! T="%s"', array($fileObject->getIdentifier()));
428 } catch (\RuntimeException $e) {
429 $this->writelog(4, 1, 120, 'Could not delete directory! Write-permission problem? Is directory "%s" empty? (You are not allowed to delete directories recursively).', array($fileObject->getIdentifier()));
430 }
431 // Log success
432 $this->writelog(4, 0, 3, 'Directory "%s" deleted', array($fileObject->getIdentifier()));
433 }
434 return $result;
435 }
436
437 /**
438 * Maps results from the fal file reference table on the
439 * structure of the normal reference index table.
440 *
441 * @param array $referenceRecord
442 * @return array
443 */
444 protected function transformFileReferenceToRecordReference(array $referenceRecord) {
445 $fileReference = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('*', 'sys_file_reference', 'uid=' . (int)$referenceRecord['recuid']);
446 return array(
447 'recuid' => $fileReference['uid_foreign'],
448 'tablename' => $fileReference['tablenames'],
449 'field' => $fileReference['fieldname'],
450 'flexpointer' => '',
451 'softref_key' => '',
452 'sorting' => $fileReference['sorting_foreign']
453 );
454 }
455
456 /**
457 * Gets a File or a Folder object from an identifier [storage]:[fileId]
458 *
459 * @param string $identifier
460 * @return \TYPO3\CMS\Core\Resource\Folder|\TYPO3\CMS\Core\Resource\File
461 */
462 protected function getFileObject($identifier) {
463 $object = $this->fileFactory->retrieveFileOrFolderObject($identifier);
464 if (!is_object($object)) {
465 throw new \TYPO3\CMS\Core\Resource\Exception\InvalidFileException('The item ' . $identifier . ' was not a file or directory!!', 1320122453);
466 }
467 return $object;
468 }
469
470 /**
471 * Copying files and folders (action=2)
472 *
473 * $cmds['data'] (string): The file/folder to copy
474 * + example "4:mypath/tomyfolder/myfile.jpg")
475 * + for backwards compatibility: the identifier was the path+filename
476 * $cmds['target'] (string): The path where to copy to.
477 * + example "2:targetpath/targetfolder/"
478 * $cmds['altName'] (string): Use an alternative name if the target already exists
479 *
480 * @param array $cmds Command details as described above
481 * @return \TYPO3\CMS\Core\Resource\File
482 */
483 protected function func_copy($cmds) {
484 if (!$this->isInit) {
485 return FALSE;
486 }
487 $sourceFileObject = $this->getFileObject($cmds['data']);
488 /** @var $targetFolderObject \TYPO3\CMS\Core\Resource\Folder */
489 $targetFolderObject = $this->getFileObject($cmds['target']);
490 // Basic check
491 if (!$targetFolderObject instanceof \TYPO3\CMS\Core\Resource\Folder) {
492 $this->writelog(2, 2, 100, 'Destination "%s" was not a directory', array($cmds['target']));
493 return FALSE;
494 }
495 // If this is TRUE, we append _XX to the file name if
496 $appendSuffixOnConflict = (string) $cmds['altName'];
497 $resultObject = NULL;
498 // Copying the file
499 if ($sourceFileObject instanceof \TYPO3\CMS\Core\Resource\File) {
500 try {
501 $conflictMode = $appendSuffixOnConflict !== '' ? 'renameNewFile' : 'cancel';
502 $resultObject = $sourceFileObject->copyTo($targetFolderObject, NULL, $conflictMode);
503 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException $e) {
504 $this->writelog(2, 1, 114, 'You are not allowed to copy files', '');
505 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
506 $this->writelog(2, 1, 110, 'Could not access all necessary resources. Source file or destination maybe was not within your mountpoints? T="%s", D="%s"', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
507 } catch (\TYPO3\CMS\Core\Resource\Exception\IllegalFileExtensionException $e) {
508 $this->writelog(2, 1, 111, 'Extension of file name "%s" is not allowed in "%s"!', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
509 } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException $e) {
510 $this->writelog(2, 1, 112, 'File "%s" already exists in folder "%s"!', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
511 } catch (\RuntimeException $e) {
512 $this->writelog(2, 2, 109, 'File "%s" WAS NOT copied to "%s"! Write-permission problem?', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
513 }
514 if ($resultObject) {
515 $this->writelog(2, 0, 1, 'File "%s" copied to "%s"', array($sourceFileObject->getIdentifier(), $resultObject->getIdentifier()));
516 }
517 } else {
518 // Else means this is a Folder
519 $sourceFolderObject = $sourceFileObject;
520 try {
521 $conflictMode = $appendSuffixOnConflict !== '' ? 'renameNewFile' : 'cancel';
522 $resultObject = $sourceFolderObject->copyTo($targetFolderObject, NULL, $conflictMode);
523 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException $e) {
524 $this->writelog(2, 1, 125, 'You are not allowed to copy directories', '');
525 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
526 $this->writelog(2, 1, 110, 'Could not access all necessary resources. Source file or destination maybe was not within your mountpoints? T="%s", D="%s"', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
527 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFolderAccessPermissionsException $e) {
528 $this->writelog(2, 1, 121, 'You don\'t have full access to the destination directory "%s"!', array($targetFolderObject->getIdentifier()));
529 } catch (\TYPO3\CMS\Core\Resource\Exception\InvalidTargetFolderException $e) {
530 $this->writelog(2, 1, 122, 'Destination cannot be inside the target! D="%s", T="%s"', array($targetFolderObject->getIdentifier(), $sourceFolderObject->getIdentifier()));
531 } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFolderException $e) {
532 $this->writelog(2, 1, 123, 'Target "%s" already exists!', array($targetFolderObject->getIdentifier()));
533 } catch (\RuntimeException $e) {
534 $this->writelog(2, 2, 119, 'Directory "%s" WAS NOT copied to "%s"! Write-permission problem?', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
535 }
536 if ($resultObject) {
537 $this->writelog(2, 0, 2, 'Directory "%s" copied to "%s"', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
538 }
539 }
540 return $resultObject;
541 }
542
543 /**
544 * Moving files and folders (action=3)
545 *
546 * $cmds['data'] (string): The file/folder to move
547 * + example "4:mypath/tomyfolder/myfile.jpg")
548 * + for backwards compatibility: the identifier was the path+filename
549 * $cmds['target'] (string): The path where to move to.
550 * + example "2:targetpath/targetfolder/"
551 * $cmds['altName'] (string): Use an alternative name if the target already exists
552 *
553 * @param array $cmds Command details as described above
554 * @return \TYPO3\CMS\Core\Resource\File
555 */
556 protected function func_move($cmds) {
557 if (!$this->isInit) {
558 return FALSE;
559 }
560 $sourceFileObject = $this->getFileObject($cmds['data']);
561 $targetFolderObject = $this->getFileObject($cmds['target']);
562 // Basic check
563 if (!$targetFolderObject instanceof \TYPO3\CMS\Core\Resource\Folder) {
564 $this->writelog(3, 2, 100, 'Destination "%s" was not a directory', array($cmds['target']));
565 return FALSE;
566 }
567 $alternativeName = (string) $cmds['altName'];
568 $resultObject = NULL;
569 // Moving the file
570 if ($sourceFileObject instanceof \TYPO3\CMS\Core\Resource\File) {
571 try {
572 if ($alternativeName !== '') {
573 // Don't allow overwriting existing files, but find a new name
574 $resultObject = $sourceFileObject->moveTo($targetFolderObject, $alternativeName, 'renameNewFile');
575 } else {
576 // Don't allow overwriting existing files
577 $resultObject = $sourceFileObject->moveTo($targetFolderObject, NULL, 'cancel');
578 }
579 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException $e) {
580 $this->writelog(3, 1, 114, 'You are not allowed to move files', '');
581 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
582 $this->writelog(3, 1, 110, 'Could not access all necessary resources. Source file or destination maybe was not within your mountpoints? T="%s", D="%s"', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
583 } catch (\TYPO3\CMS\Core\Resource\Exception\IllegalFileExtensionException $e) {
584 $this->writelog(3, 1, 111, 'Extension of file name "%s" is not allowed in "%s"!', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
585 } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException $e) {
586 $this->writelog(3, 1, 112, 'File "%s" already exists in folder "%s"!', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
587 } catch (\RuntimeException $e) {
588 $this->writelog(3, 2, 109, 'File "%s" WAS NOT copied to "%s"! Write-permission problem?', array($sourceFileObject->getIdentifier(), $targetFolderObject->getIdentifier()));
589 }
590 $this->writelog(3, 0, 1, 'File "%s" moved to "%s"', array($sourceFileObject->getIdentifier(), $resultObject->getIdentifier()));
591 } else {
592 // Else means this is a Folder
593 $sourceFolderObject = $sourceFileObject;
594 try {
595 if ($alternativeName !== '') {
596 // Don't allow overwriting existing files, but find a new name
597 $resultObject = $sourceFolderObject->moveTo($targetFolderObject, $alternativeName, 'renameNewFile');
598 } else {
599 // Don't allow overwriting existing files
600 $resultObject = $sourceFolderObject->moveTo($targetFolderObject, NULL, 'renameNewFile');
601 }
602 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException $e) {
603 $this->writelog(3, 1, 125, 'You are not allowed to move directories', '');
604 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileAccessPermissionsException $e) {
605 $this->writelog(3, 1, 110, 'Could not access all necessary resources. Source file or destination maybe was not within your mountpoints? T="%s", D="%s"', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
606 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFolderAccessPermissionsException $e) {
607 $this->writelog(3, 1, 121, 'You don\'t have full access to the destination directory "%s"!', array($targetFolderObject->getIdentifier()));
608 } catch (\TYPO3\CMS\Core\Resource\Exception\InvalidTargetFolderException $e) {
609 $this->writelog(3, 1, 122, 'Destination cannot be inside the target! D="%s", T="%s"', array($targetFolderObject->getIdentifier(), $sourceFolderObject->getIdentifier()));
610 } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFolderException $e) {
611 $this->writelog(3, 1, 123, 'Target "%s" already exists!', array($targetFolderObject->getIdentifier()));
612 } catch (\RuntimeException $e) {
613 $this->writelog(3, 2, 119, 'Directory "%s" WAS NOT moved to "%s"! Write-permission problem?', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
614 }
615 $this->writelog(3, 0, 2, 'Directory "%s" moved to "%s"', array($sourceFolderObject->getIdentifier(), $targetFolderObject->getIdentifier()));
616 }
617 return $resultObject;
618 }
619
620 /**
621 * Renaming files or foldes (action=5)
622 *
623 * $cmds['data'] (string): The file/folder to copy
624 * + example "4:mypath/tomyfolder/myfile.jpg")
625 * + for backwards compatibility: the identifier was the path+filename
626 * $cmds['target'] (string): New name of the file/folder
627 *
628 * @param array $cmds Command details as described above
629 * @return \TYPO3\CMS\Core\Resource\File Returns the new file upon success
630 * @todo Define visibility
631 */
632 public function func_rename($cmds) {
633 if (!$this->isInit) {
634 return FALSE;
635 }
636 $sourceFileObject = $this->getFileObject($cmds['data']);
637 $targetFile = $cmds['target'];
638 $resultObject = NULL;
639 if ($sourceFileObject instanceof \TYPO3\CMS\Core\Resource\File) {
640 try {
641 // Try to rename the File
642 $resultObject = $sourceFileObject->rename($targetFile);
643 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException $e) {
644 $this->writelog(5, 1, 102, 'You are not allowed to rename files!', '');
645 } catch (\TYPO3\CMS\Core\Resource\Exception\IllegalFileExtensionException $e) {
646 $this->writelog(5, 1, 101, 'Extension of file name "%s" was not allowed!', array($targetFile));
647 } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException $e) {
648 $this->writelog(5, 1, 120, 'Destination "%s" existed already!', array($targetFile));
649 } catch (\TYPO3\CMS\Core\Resource\Exception\NotInMountPointException $e) {
650 $this->writelog(5, 1, 121, 'Destination path "%s" was not within your mountpoints!', array($targetFile));
651 } catch (\RuntimeException $e) {
652 $this->writelog(5, 1, 100, 'File "%s" was not renamed! Write-permission problem in "%s"?', array($sourceFileObject->getName(), $targetFile));
653 }
654 $this->writelog(5, 0, 1, 'File renamed from "%s" to "%s"', array($sourceFileObject->getName(), $targetFile));
655 } else {
656 // Else means this is a Folder
657 try {
658 // Try to rename the Folder
659 $resultObject = $sourceFileObject->rename($targetFile);
660 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException $e) {
661 $this->writelog(5, 1, 111, 'You are not allowed to rename directories!', '');
662 } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException $e) {
663 $this->writelog(5, 1, 120, 'Destination "%s" existed already!', array($targetFile));
664 } catch (\TYPO3\CMS\Core\Resource\Exception\NotInMountPointException $e) {
665 $this->writelog(5, 1, 121, 'Destination path "%s" was not within your mountpoints!', array($targetFile));
666 } catch (\RuntimeException $e) {
667 $this->writelog(5, 1, 110, 'Directory "%s" was not renamed! Write-permission problem in "%s"?', array($sourceFileObject->getName(), $targetFile));
668 }
669 $this->writelog(5, 0, 2, 'Directory renamed from "%s" to "%s"', array($sourceFileObject->getName(), $targetFile));
670 }
671 return $resultObject;
672 }
673
674 /**
675 * This creates a new folder. (action=6)
676 *
677 * $cmds['data'] (string): The new folder name
678 * $cmds['target'] (string): The path where to copy to.
679 * + example "2:targetpath/targetfolder/"
680 *
681 * @param array $cmds Command details as described above
682 * @return \TYPO3\CMS\Core\Resource\Folder Returns the new foldername upon success
683 * @todo Define visibility
684 */
685 public function func_newfolder($cmds) {
686 if (!$this->isInit) {
687 return FALSE;
688 }
689 $targetFolderObject = $this->getFileObject($cmds['target']);
690 if (!$targetFolderObject instanceof \TYPO3\CMS\Core\Resource\Folder) {
691 $this->writelog(6, 2, 104, 'Destination "%s" was not a directory', array($cmds['target']));
692 return FALSE;
693 }
694 $resultObject = NULL;
695 try {
696 $folderName = $cmds['data'];
697 $resultObject = $targetFolderObject->createFolder($folderName);
698 $this->writelog(6, 0, 1, 'Directory "%s" created in "%s"', array($folderName, $targetFolderObject->getIdentifier() . '/'));
699 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFolderWritePermissionsException $e) {
700 $this->writelog(6, 1, 103, 'You are not allowed to create directories!', '');
701 } catch (\TYPO3\CMS\Core\Resource\Exception\NotInMountPointException $e) {
702 $this->writelog(6, 1, 102, 'Destination path "%s" was not within your mountpoints!', array($targetFolderObject->getIdentifier() . '/'));
703 } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFolderException $e) {
704 $this->writelog(6, 1, 101, 'File or directory "%s" existed already!', array($folderName));
705 } catch (\RuntimeException $e) {
706 $this->writelog(6, 1, 100, 'Directory "%s" not created. Write-permission problem in "%s"?', array($folderName, $targetFolderObject->getIdentifier() . '/'));
707 }
708 return $resultObject;
709 }
710
711 /**
712 * This creates a new file. (action=8)
713 * $cmds['data'] (string): The new file name
714 * $cmds['target'] (string): The path where to create it.
715 * + example "2:targetpath/targetfolder/"
716 *
717 * @param array $cmds Command details as described above
718 * @return string Returns the new filename upon success
719 * @todo Define visibility
720 */
721 public function func_newfile($cmds) {
722 if (!$this->isInit) {
723 return FALSE;
724 }
725 $targetFolderObject = $this->getFileObject($cmds['target']);
726 if (!$targetFolderObject instanceof \TYPO3\CMS\Core\Resource\Folder) {
727 $this->writelog(8, 2, 104, 'Destination "%s" was not a directory', array($cmds['target']));
728 return FALSE;
729 }
730 $resultObject = NULL;
731 try {
732 $fileName = $cmds['data'];
733 $resultObject = $targetFolderObject->createFile($fileName);
734 $this->writelog(8, 0, 1, 'File created: "%s"', array($fileName));
735 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFolderWritePermissionsException $e) {
736 $this->writelog(8, 1, 103, 'You are not allowed to create files!', '');
737 } catch (\TYPO3\CMS\Core\Resource\Exception\NotInMountPointException $e) {
738 $this->writelog(8, 1, 102, 'Destination path "%s" was not within your mountpoints!', array($targetFolderObject->getIdentifier()));
739 } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException $e) {
740 $this->writelog(8, 1, 101, 'File existed already in "%s"!', array($targetFolderObject->getIdentifier()));
741 } catch (\TYPO3\CMS\Core\Resource\Exception\InvalidFileNameException $e) {
742 $this->writelog(8, 1, 106, 'File name "%s" was not allowed!', $fileName);
743 } catch (\RuntimeException $e) {
744 $this->writelog(8, 1, 100, 'File "%s" was not created! Write-permission problem in "%s"?', array($fileName, $targetFolderObject->getIdentifier()));
745 }
746 return $resultObject;
747 }
748
749 /**
750 * Editing textfiles or folders (action=9)
751 *
752 * @param array $cmds $cmds['data'] is the new content. $cmds['target'] is the target (file or dir)
753 * @return boolean Returns TRUE on success
754 * @todo Define visibility
755 */
756 public function func_edit($cmds) {
757 if (!$this->isInit) {
758 return FALSE;
759 }
760 // Example indentifier for $cmds['target'] => "4:mypath/tomyfolder/myfile.jpg"
761 // for backwards compatibility: the combined file identifier was the path+filename
762 $fileIdentifier = $cmds['target'];
763 $fileObject = $this->getFileObject($fileIdentifier);
764 // Example indentifier for $cmds['target'] => "2:targetpath/targetfolder/"
765 $content = $cmds['data'];
766 if (!$fileObject instanceof \TYPO3\CMS\Core\Resource\File) {
767 $this->writelog(9, 2, 123, 'Target "%s" was not a file!', array($fileIdentifier));
768 return FALSE;
769 }
770 $extList = $GLOBALS['TYPO3_CONF_VARS']['SYS']['textfile_ext'];
771 if (!\TYPO3\CMS\Core\Utility\GeneralUtility::inList($extList, $fileObject->getExtension())) {
772 $this->writelog(9, 1, 102, 'File extension "%s" is not a textfile format! (%s)', array($fileObject->getExtension(), $extList));
773 return FALSE;
774 }
775 try {
776 $fileObject->setContents($content);
777 clearstatcache();
778 $this->writelog(9, 0, 1, 'File saved to "%s", bytes: %s, MD5: %s ', array($fileObject->getIdentifier(), $fileObject->getSize(), md5($content)));
779 return TRUE;
780 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException $e) {
781 $this->writelog(9, 1, 104, 'You are not allowed to edit files!', '');
782 return FALSE;
783 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFileWritePermissionsException $e) {
784 $this->writelog(9, 1, 100, 'File "%s" was not saved! Write-permission problem?', array($fileObject->getIdentifier()));
785 return FALSE;
786 }
787 }
788
789 /**
790 * Upload of files (action=1)
791 * when having multiple uploads (HTML5-style), the array $_FILES looks like this:
792 * Array(
793 * [upload_1] => Array(
794 * [name] => Array(
795 * [0] => GData - Content-Elements and Media-Gallery.pdf
796 * [1] => CMS Expo 2011.txt
797 * )
798 * [type] => Array(
799 * [0] => application/pdf
800 * [1] => text/plain
801 * )
802 * [tmp_name] => Array(
803 * [0] => /Applications/MAMP/tmp/php/phpNrOB43
804 * [1] => /Applications/MAMP/tmp/php/phpD2HQAK
805 * )
806 * [size] => Array(
807 * [0] => 373079
808 * [1] => 1291
809 * )
810 * )
811 * )
812 * in HTML you'd need sth like this: <input type="file" name="upload_1[]" multiple="true" />
813 *
814 * @param array $cmds $cmds['data'] is the ID-number (points to the global var that holds the filename-ref ($_FILES['upload_' . $id]['name']) . $cmds['target'] is the target directory, $cmds['charset'] is the the character set of the file name (utf-8 is needed for JS-interaction)
815 * @return string Returns the new filename upon success
816 * @todo Define visibility
817 */
818 public function func_upload($cmds) {
819 if (!$this->isInit) {
820 return FALSE;
821 }
822 $uploadPosition = $cmds['data'];
823 $uploadedFileData = $_FILES['upload_' . $uploadPosition];
824 if (empty($uploadedFileData['name']) || is_array($uploadedFileData['name']) && empty($uploadedFileData['name'][0])) {
825 $this->writelog(1, 2, 108, 'No file was uploaded!', '');
826 return FALSE;
827 }
828 // Example indentifier for $cmds['target'] => "2:targetpath/targetfolder/"
829 $targetFolderObject = $this->getFileObject($cmds['target']);
830 // Uploading with non HTML-5-style, thus, make an array out of it, so we can loop over it
831 if (!is_array($uploadedFileData['name'])) {
832 $uploadedFileData = array(
833 'name' => array($uploadedFileData['name']),
834 'type' => array($uploadedFileData['type']),
835 'tmp_name' => array($uploadedFileData['tmp_name']),
836 'size' => array($uploadedFileData['size'])
837 );
838 }
839 $resultObjects = array();
840 $numberOfUploadedFilesForPosition = count($uploadedFileData['name']);
841 // Loop through all uploaded files
842 for ($i = 0; $i < $numberOfUploadedFilesForPosition; $i++) {
843 $fileInfo = array(
844 'name' => $uploadedFileData['name'][$i],
845 'type' => $uploadedFileData['type'][$i],
846 'tmp_name' => $uploadedFileData['tmp_name'][$i],
847 'size' => $uploadedFileData['size'][$i]
848 );
849 try {
850 // @todo can be improved towards conflict mode naming
851 if ($this->dontCheckForUnique) {
852 $conflictMode = 'replace';
853 } else {
854 $conflictMode = 'cancel';
855 }
856 $resultObjects[] = $targetFolderObject->addUploadedFile($fileInfo, $conflictMode);
857 $this->writelog(1, 0, 1, 'Uploading file "%s" to "%s"', array($fileInfo['name'], $targetFolderObject->getIdentifier()));
858 } catch (\TYPO3\CMS\Core\Resource\Exception\UploadException $e) {
859 $this->writelog(1, 2, 106, 'The upload has failed, no uploaded file found!', '');
860 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientUserPermissionsException $e) {
861 $this->writelog(1, 1, 105, 'You are not allowed to upload files!', '');
862 } catch (\TYPO3\CMS\Core\Resource\Exception\UploadSizeException $e) {
863 $this->writelog(1, 1, 104, 'The uploaded file "%s" exceeds the size-limit', array($fileInfo['name']));
864 } catch (\TYPO3\CMS\Core\Resource\Exception\InsufficientFolderWritePermissionsException $e) {
865 $this->writelog(1, 1, 103, 'Destination path "%s" was not within your mountpoints!', array($targetFolderObject->getIdentifier()));
866 } catch (\TYPO3\CMS\Core\Resource\Exception\IllegalFileExtensionException $e) {
867 $this->writelog(1, 1, 102, 'Extension of file name "%s" is not allowed in "%s"!', array($fileInfo['name'], $targetFolderObject->getIdentifier()));
868 } catch (\TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException $e) {
869 $this->writelog(1, 1, 101, 'No unique filename available in "%s"!', array($targetFolderObject->getIdentifier()));
870 } catch (\RuntimeException $e) {
871 $this->writelog(1, 1, 100, 'Uploaded file could not be moved! Write-permission problem in "%s"?', array($targetFolderObject->getIdentifier()));
872 }
873 }
874 return $resultObjects;
875 }
876
877 /**
878 * Unzipping file (action=7)
879 * This is permitted only if the user has fullAccess or if the file resides
880 *
881 * @param array $cmds $cmds['data'] is the zip-file. $cmds['target'] is the target directory. If not set we'll default to the same directory as the file is in.
882 * @return boolean Returns TRUE on success
883 * @todo Define visibility
884 */
885 public function func_unzip($cmds) {
886 if (!$this->isInit || $this->dont_use_exec_commands) {
887 return FALSE;
888 }
889 $theFile = $cmds['data'];
890 if (!@is_file($theFile)) {
891 $this->writelog(7, 2, 105, 'The file "%s" did not exist!', array($theFile));
892 return FALSE;
893 }
894 $fI = \TYPO3\CMS\Core\Utility\GeneralUtility::split_fileref($theFile);
895 if (!isset($cmds['target'])) {
896 $cmds['target'] = $fI['path'];
897 }
898 // Clean up destination directory
899 // !!! Method has been put in the local driver, can be saftely removed
900 $theDest = $this->is_directory($cmds['target']);
901 if (!$theDest) {
902 $this->writelog(7, 2, 104, 'Destination "%s" was not a directory', array($cmds['target']));
903 return FALSE;
904 }
905 if (!$this->actionPerms['unzipFile']) {
906 $this->writelog(7, 1, 103, 'You are not allowed to unzip files', '');
907 return FALSE;
908 }
909 if ($fI['fileext'] != 'zip') {
910 $this->writelog(7, 1, 102, 'File extension is not "zip"', '');
911 return FALSE;
912 }
913 if (!$this->checkIfFullAccess($theDest)) {
914 $this->writelog(7, 1, 101, 'You don\'t have full access to the destination directory "%s"!', array($theDest));
915 return FALSE;
916 }
917 // !!! Method has been put in the sotrage driver, can be saftely removed
918 if ($this->checkPathAgainstMounts($theFile) && $this->checkPathAgainstMounts($theDest . '/')) {
919 // No way to do this under windows.
920 $cmd = $this->unzipPath . 'unzip -qq ' . escapeshellarg($theFile) . ' -d ' . escapeshellarg($theDest);
921 \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd);
922 $this->writelog(7, 0, 1, 'Unzipping file "%s" in "%s"', array($theFile, $theDest));
923 return TRUE;
924 } else {
925 $this->writelog(7, 1, 100, 'File "%s" or destination "%s" was not within your mountpoints!', array($theFile, $theDest));
926 return FALSE;
927 }
928 }
929
930 }
931
932
933 ?>