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