* Fixed bug #1861: Call of inexinsting t3lib_exec::imageMagickCommand() instead of...
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_basicfilefunc.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2005 Kasper Skaarhoj (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 * Contains class with basic file management functions
29 *
30 * $Id$
31 * Revised for TYPO3 3.6 July/2003 by Kasper Skaarhoj
32 *
33 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
34 */
35 /**
36 * [CLASS/FUNCTION INDEX of SCRIPT]
37 *
38 *
39 *
40 * 81: class t3lib_basicFileFunctions
41 *
42 * SECTION: Checking functions
43 * 133: function init($mounts, $f_ext)
44 * 150: function getTotalFileInfo($wholePath)
45 * 170: function is_allowed($iconkey,$type)
46 * 195: function checkIfFullAccess($theDest)
47 * 209: function is_webpath($path)
48 * 229: function checkIfAllowed($ext, $theDest, $filename='')
49 * 239: function checkFileNameLen($fileName)
50 * 249: function is_directory($theDir)
51 * 266: function isPathValid($theFile)
52 * 281: function getUniqueName($theFile, $theDest, $dontCheckForUnique=0)
53 * 324: function checkPathAgainstMounts($thePath)
54 * 340: function findFirstWebFolder()
55 * 360: function blindPath($thePath)
56 * 376: function findTempFolder()
57 *
58 * SECTION: Cleaning functions
59 * 410: function cleanDirectoryName($theDir)
60 * 420: function rmDoubleSlash($string)
61 * 430: function slashPath($path)
62 * 443: function cleanFileName($fileName)
63 * 454: function formatSize($sizeInBytes)
64 *
65 * TOTAL FUNCTIONS: 19
66 * (This index is automatically created/updated by the extension "extdeveval")
67 *
68 */
69
70 require_once(PATH_t3lib.'class.t3lib_cs.php');
71
72
73 /**
74 * Contains functions for management, validation etc of files in TYPO3, using the concepts of web- and ftp-space. Please see the comment for the init() function
75 *
76 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
77 * @package TYPO3
78 * @subpackage t3lib
79 * @see t3lib_basicFileFunctions::init()
80 */
81 class t3lib_basicFileFunctions {
82 var $getUniqueNamePrefix = ''; // Prefix which will be prepended the file when using the getUniqueName-function
83 var $maxNumber = 20; // This number decides the highest allowed appended number used on a filename before we use naming with unique strings
84 var $uniquePrecision = 6; // This number decides how many characters out of a unique MD5-hash that is appended to a filename if getUniqueName is asked to find an available filename.
85 var $maxInputNameLen = 60; // This is the maximum length of names treated by cleanFileName()
86 var $tempFN = '_temp_'; // Temp-foldername. A folder in the root of one of the mounts with this name is regarded a TEMP-folder (used for upload from clipboard)
87
88 // internal
89 var $f_ext = Array(); // See comment in header
90 var $mounts = Array(); // See comment in header
91 var $webPath =''; // Set to DOCUMENT_ROOT.
92 var $isInit = 0; // Set to true after init()/start();
93
94
95
96 /**********************************
97 *
98 * Checking functions
99 *
100 **********************************/
101
102 /**
103 * Constructor
104 * This function should be called to initialise the internal arrays $this->mounts and $this->f_ext
105 *
106 * A typical example of the array $mounts is this:
107 * $mounts[xx][path] = (..a mounted path..)
108 * the 'xx'-keys is just numerical from zero. There are also a [name] and [type] value that just denotes the mountname and type. Not used for athentication here.
109 * $this->mounts is traversed in the function checkPathAgainstMounts($thePath), and it is checked that $thePath is actually below one of the mount-paths
110 * The mountpaths are with a trailing '/'. $thePath must be with a trailing '/' also!
111 * As you can see, $this->mounts is very critical! This is the array that decides where the user will be allowed to copy files!!
112 * Typically the global var $WEBMOUNTS would be passed along as $mounts
113 *
114 * A typical example of the array $f_ext is this:
115 * $f_ext['webspace']['allow']='';
116 * $f_ext['webspace']['deny']='php3,php';
117 * $f_ext['ftpspace']['allow']='*';
118 * $f_ext['ftpspace']['deny']='';
119 * The control of fileextensions goes in two catagories. Webspace and Ftpspace. Webspace is folders accessible from a webbrowser (below TYPO3_DOCUMENT_ROOT) and ftpspace is everything else.
120 * The control is done like this: If an extension matches 'allow' then the check returns true. If not and an extension matches 'deny' then the check return false. If no match at all, returns true.
121 * You list extensions comma-separated. If the value is a '*' every extension is allowed
122 * The list is case-insensitive when used in this class (see init())
123 * Typically TYPO3_CONF_VARS['BE']['fileExtensions'] would be passed along as $f_ext.
124 *
125 * Example:
126 * $basicff->init($GLOBALS['FILEMOUNTS'],$TYPO3_CONF_VARS['BE']['fileExtensions']);
127 *
128 * @param array Contains the paths of the file mounts for the current BE user. Normally $GLOBALS['FILEMOUNTS'] is passed. This variable is set during backend user initialization; $FILEMOUNTS = $BE_USER->returnFilemounts(); (see typo3/init.php)
129 * @param array Array with information about allowed and denied file extensions. Typically passed: $TYPO3_CONF_VARS['BE']['fileExtensions']
130 * @return void
131 * @see typo3/init.php, t3lib_userAuthGroup::returnFilemounts()
132 */
133 function init($mounts, $f_ext) {
134 $this->f_ext['webspace']['allow'] = t3lib_div::uniqueList(strtolower($f_ext['webspace']['allow']));
135 $this->f_ext['webspace']['deny'] = t3lib_div::uniqueList(strtolower($f_ext['webspace']['deny']));
136 $this->f_ext['ftpspace']['allow'] = t3lib_div::uniqueList(strtolower($f_ext['ftpspace']['allow']));
137 $this->f_ext['ftpspace']['deny'] = t3lib_div::uniqueList(strtolower($f_ext['ftpspace']['deny']));
138
139 $this->mounts = $mounts;
140 $this->webPath = t3lib_div::getIndpEnv('TYPO3_DOCUMENT_ROOT');
141 $this->isInit = 1;
142 }
143
144 /**
145 * Returns an array with a whole lot of fileinformation.
146 *
147 * @param string Filepath to existing file. Should probably be absolute. Filefunctions are performed on this value.
148 * @return array Information about the file in the filepath
149 */
150 function getTotalFileInfo($wholePath) {
151 $theuser = getmyuid();
152 $info = t3lib_div::split_fileref($wholePath);
153 $info['tstamp'] = @filectime($wholePath);
154 $info['size'] = @filesize($wholePath);
155 $info['type'] = @filetype($wholePath);
156 $info['owner'] = @fileowner($wholePath);
157 $info['perms'] = @fileperms($wholePath);
158 $info['writable'] = !@is_writable($wholePath);
159 $info['readable'] = !@is_readable($wholePath);
160 return $info;
161 }
162
163 /**
164 * Checks if a $iconkey (fileextension) is allowed according to $this->f_ext.
165 *
166 * @param string The extension to check, eg. "php" or "html" etc.
167 * @param string Either "webspage" or "ftpspace" - points to a key in $this->f_ext
168 * @return boolean True if file extension is allowed.
169 */
170 function is_allowed($iconkey,$type) {
171 if (isset($this->f_ext[$type])) {
172 $ik = strtolower($iconkey);
173 if ($ik) {
174 // If the extension is found amongst the allowed types, we return true immediately
175 if ($this->f_ext[$type]['allow']=='*' || t3lib_div::inList($this->f_ext[$type]['allow'],$ik)) return true;
176 // If the extension is found amongst the denied types, we return false immediately
177 if ($this->f_ext[$type]['deny']=='*' || t3lib_div::inList($this->f_ext[$type]['deny'],$ik)) return false;
178 // If no match we return true
179 return true;
180 } else { // If no extension:
181 if ($this->f_ext[$type]['allow']=='*') return true;
182 if ($this->f_ext[$type]['deny']=='*') return false;
183 return true;
184 }
185 }
186 return false;
187 }
188
189 /**
190 * Returns true if you can operate of ANY file ('*') in the space $theDest is in ('webspace' / 'ftpspace')
191 *
192 * @param string Absolute path
193 * @return boolean
194 */
195 function checkIfFullAccess($theDest) {
196 $type = $this->is_webpath($theDest)?'webspace':'ftpspace';
197 if (isset($this->f_ext[$type])) {
198 if ((string)$this->f_ext[$type]['deny']=='' || $this->f_ext[$type]['allow']=='*') return true;
199 }
200 }
201
202 /**
203 * Checks if $this->webPath (should be TYPO3_DOCUMENT_ROOT) is in the first part of $path
204 * Returns true also if $this->init is not set or if $path is empty...
205 *
206 * @param string Absolute path to check
207 * @return boolean
208 */
209 function is_webpath($path) {
210 if ($this->isInit) {
211 $testPath = $this->slashPath($path);
212 $testPathWeb = $this->slashPath($this->webPath);
213 if ($testPathWeb && $testPath) {
214 return t3lib_div::isFirstPartOfStr($testPath,$testPathWeb);
215 }
216 }
217 return true; // Its more safe to return true (as the webpath is more restricted) if something went wrong...
218 }
219
220 /**
221 * If the filename is given, check it against the TYPO3_CONF_VARS[BE][fileDenyPattern] +
222 * Checks if the $ext fileextension is allowed in the path $theDest (this is based on whether $theDest is below the $this->webPath)
223 *
224 * @param string File extension, eg. "php" or "html"
225 * @param string Absolute path for which to test
226 * @param string Filename to check against TYPO3_CONF_VARS[BE][fileDenyPattern]
227 * @return boolean True if extension/filename is allowed
228 */
229 function checkIfAllowed($ext, $theDest, $filename='') {
230 return t3lib_div::verifyFilenameAgainstDenyPattern($filename) && $this->is_allowed($ext,($this->is_webpath($theDest)?'webspace':'ftpspace'));
231 }
232
233 /**
234 * Returns true if the input filename string is shorter than $this->maxInputNameLen.
235 *
236 * @param string Filename, eg "somefile.html"
237 * @return boolean
238 */
239 function checkFileNameLen($fileName) {
240 return strlen($fileName) <= $this->maxInputNameLen;
241 }
242
243 /**
244 * Cleans $theDir for slashes in the end of the string and returns the new path, if it exists on the server.
245 *
246 * @param string Directory path to check
247 * @return string Returns the cleaned up directory name if OK, otherwise false.
248 */
249 function is_directory($theDir) {
250 if ($this->isPathValid($theDir)) {
251 $theDir=$this->cleanDirectoryName($theDir);
252 if (@is_dir($theDir)) {
253 return $theDir;
254 }
255 }
256 return false;
257 }
258
259 /**
260 * Wrapper for t3lib_div::validPathStr()
261 *
262 * @param string Filepath to evaluate
263 * @return boolean True, if no '//', '..' or '\' is in the $theFile
264 * @see t3lib_div::validPathStr()
265 */
266 function isPathValid($theFile) {
267 return t3lib_div::validPathStr($theFile);
268 }
269
270 /**
271 * Returns the destination path/filename of a unique filename/foldername in that path.
272 * If $theFile exists in $theDest (directory) the file have numbers appended up to $this->maxNumber. Hereafter a unique string will be appended.
273 * This function is used by fx. TCEmain when files are attached to records and needs to be uniquely named in the uploads/* folders
274 *
275 * @param string The input filename to check
276 * @param string The directory for which to return a unique filename for $theFile. $theDest MUST be a valid directory. Should be absolute.
277 * @param boolean If set the filename is returned with the path prepended without checking whether it already existed!
278 * @return string The destination absolute filepath (not just the name!) of a unique filename/foldername in that path.
279 * @see t3lib_TCEmain::checkValue()
280 */
281 function getUniqueName($theFile, $theDest, $dontCheckForUnique=0) {
282 $theDest = $this->is_directory($theDest); // $theDest is cleaned up
283 $origFileInfo = t3lib_div::split_fileref($theFile); // Fetches info about path, name, extention of $theFile
284 if ($theDest) {
285 if ($this->getUniqueNamePrefix) { // Adds prefix
286 $origFileInfo['file'] = $this->getUniqueNamePrefix.$origFileInfo['file'];
287 $origFileInfo['filebody'] = $this->getUniqueNamePrefix.$origFileInfo['filebody'];
288 }
289
290 // Check if the file exists and if not - return the filename...
291 $fileInfo = $origFileInfo;
292 $theDestFile = $theDest.'/'.$fileInfo['file']; // The destinations file
293 if (!@file_exists($theDestFile) || $dontCheckForUnique) { // If the file does NOT exist we return this filename
294 return $theDestFile;
295 }
296
297 // Well the filename in its pure form existed. Now we try to append numbers / unique-strings and see if we can find an available filename...
298 $theTempFileBody = preg_replace('/_[0-9][0-9]$/','',$origFileInfo['filebody']); // This removes _xx if appended to the file
299 $theOrigExt = $origFileInfo['realFileext'] ? '.'.$origFileInfo['realFileext'] : '';
300
301 for ($a=1; $a<=($this->maxNumber+1); $a++) {
302 if ($a<=$this->maxNumber) { // First we try to append numbers
303 $insert = '_'.sprintf('%02d', $a);
304 } else { // .. then we try unique-strings...
305 $insert = '_'.substr(md5(uniqId('')),0,$this->uniquePrecision);
306 }
307 $theTestFile = $theTempFileBody.$insert.$theOrigExt;
308 $theDestFile = $theDest.'/'.$theTestFile; // The destinations file
309 if (!@file_exists($theDestFile)) { // If the file does NOT exist we return this filename
310 return $theDestFile;
311 }
312 }
313 }
314 }
315
316 /**
317 * Checks if $thePath is a path under one of the paths in $this->mounts
318 * See comment in the header of this class.
319 *
320 * @param string $thePath MUST HAVE a trailing '/' in order to match correctly with the mounts
321 * @return string The key to the first mount found, otherwise nothing is returned.
322 * @see init()
323 */
324 function checkPathAgainstMounts($thePath) {
325 if ($thePath && $this->isPathValid($thePath) && is_array($this->mounts)) {
326 reset ($this->mounts);
327 while(list($k,$val)=each($this->mounts)) {
328 if (t3lib_div::isFirstPartOfStr($thePath,$val['path'])) {
329 return $k;
330 }
331 }
332 }
333 }
334
335 /**
336 * Find first web folder (relative to PATH_site.'fileadmin') in filemounts array
337 *
338 * @return string The key to the first mount inside PATH_site."fileadmin" found, otherwise nothing is returned.
339 */
340 function findFirstWebFolder() {
341 global $TYPO3_CONF_VARS;
342
343 if (is_array($this->mounts)) {
344 reset ($this->mounts);
345 while(list($k,$val)=each($this->mounts)) {
346 if (t3lib_div::isFirstPartOfStr($val['path'], PATH_site.$TYPO3_CONF_VARS['BE']['fileadminDir'])) {
347 return $k;
348 }
349 }
350 }
351 }
352
353 /**
354 * Removes filemount part of a path, thus blinding the position.
355 * Takes a path, $thePath, and removes the part of the path which equals the filemount.
356 *
357 * @param string $thePath is a path which MUST be found within one of the internally set filemounts, $this->mounts
358 * @return string The processed input path
359 */
360 function blindPath($thePath) {
361 $k=$this->checkPathAgainstMounts($thePath);
362 if ($k) {
363 $name='';
364 $name.='['.$this->mounts[$k]['name'].']: ';
365 $name.=substr($thePath,strlen($this->mounts[$k]['path']));
366 return $name;
367 }
368 }
369
370 /**
371 * Find temporary folder
372 * Finds the first $this->tempFN ('_temp_' usually) -folder in the internal array of filemounts, $this->mounts
373 *
374 * @return string Returns the path if found, otherwise nothing if error.
375 */
376 function findTempFolder() {
377 if ($this->tempFN && is_array($this->mounts)) {
378 reset ($this->mounts);
379 while(list($k,$val)=each($this->mounts)) {
380 $tDir = $val['path'].$this->tempFN;
381 if (@is_dir($tDir)) {
382 return $tDir;
383 }
384 }
385 }
386 }
387
388
389
390
391
392
393
394
395
396
397
398 /*********************
399 *
400 * Cleaning functions
401 *
402 *********************/
403
404 /**
405 * Removes all dots, slashes and spaces after a path...
406 *
407 * @param string Input string
408 * @return string Output string
409 */
410 function cleanDirectoryName($theDir) {
411 return preg_replace('/[\/\. ]*$/','',$this->rmDoubleSlash($theDir));
412 }
413
414 /**
415 * Converts any double slashes (//) to a single slash (/)
416 *
417 * @param string Input value
418 * @return string Returns the converted string
419 */
420 function rmDoubleSlash($string) {
421 return str_replace('//','/',$string);
422 }
423
424 /**
425 * Returns a string which has a slash '/' appended if it doesn't already have that slash
426 *
427 * @param string Input string
428 * @return string Output string with a slash in the end (if not already there)
429 */
430 function slashPath($path) {
431 if (substr($path,-1)!='/') {
432 return $path.'/';
433 }
434 return $path;
435 }
436
437 /**
438 * Returns a string where any character not matching [.a-zA-Z0-9_-] is substituted by '_'
439 *
440 * @param string Input string, typically the body of a filename
441 * @param string Charset of the a filename (defaults to current charset; depending on context)
442 * @return string Output string with any characters not matching [.a-zA-Z0-9_-] is substituted by '_'
443 */
444 function cleanFileName($fileName,$charset='') {
445 if (!is_object($this->csConvObj)) {
446 if (TYPO3_MODE=='FE') {
447 $this->csConvObj = &$GLOBALS['TSFE']->csConvObj;
448 } elseif (is_object($GLOBALS['LANG'])) { // BE assumed:
449 $this->csConvObj = &$GLOBALS['LANG']->csConvObj;
450 } else { // The object may not exist yet, so we need to create it now. Happens in the Install Tool for example.
451 $this->csConvObj = &t3lib_div::makeInstance('t3lib_cs');
452 }
453 }
454
455 if (!$charset) {
456 if (TYPO3_MODE=='FE') {
457 $charset = $GLOBALS['TSFE']->renderCharset;
458 } elseif (is_object($GLOBALS['LANG'])) { // BE assumed:
459 $charset = $GLOBALS['LANG']->charSet;
460 } else { // best guess
461 $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
462 }
463 }
464
465 if ($charset) {
466 $fileName = $this->csConvObj->specCharsToASCII($charset,$fileName);
467 }
468
469 return preg_replace('/[^.[:alnum:]_-]/','_',trim($fileName));
470 }
471
472 /**
473 * Formats an integer, $sizeInBytes, to Mb or Kb or just bytes
474 *
475 * @param integer Bytes to be formated
476 * @return string Formatted with M,K or &nbsp;&nbsp; appended.
477 */
478 function formatSize($sizeInBytes) {
479 if ($sizeInBytes>900) {
480 if ($sizeInBytes>900000) { // MB
481 $val = $sizeInBytes/(1024*1024);
482 return number_format($val, (($val<20)?1:0), '.', '').' M';
483 } else { // KB
484 $val = $sizeInBytes/(1024);
485 return number_format($val, (($val<20)?1:0), '.', '').' K';
486 }
487 } else { // Bytes
488 return $sizeInBytes.'&nbsp;&nbsp;';
489 }
490 }
491 }
492
493
494
495 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_basicfilefunc.php']) {
496 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_basicfilefunc.php']);
497 }
498 ?>