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