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