FileUtility.php 17.4 KB
Newer Older
1
<?php
2 3
namespace T3o\TerFe2\Utility;

4 5
/*
 * This file is part of the TYPO3 CMS project.
6
 *
7 8 9
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
10
 *
11 12
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
13
 *
14 15
 * The TYPO3 project - inspiring people to share!
 */
16 17 18 19

/**
 * Utilities to manage files
 */
20
class FileUtility
21 22 23 24 25 26
{

    /**
     * Check if a file, URL or directory exists
     *
     * @param string $filename Path to the file
27
     * @return bool TRUE if file exists
28 29 30 31
     */
    public static function fileExists($filename)
    {
        if (empty($filename)) {
Markus Sommer's avatar
Markus Sommer committed
32
            return false;
33 34 35 36 37 38 39
        }

        if (is_dir($filename)) {
            return (bool)file_exists($filename);
        }

        $handle = @fopen($filename, 'r');
Markus Sommer's avatar
Markus Sommer committed
40
        if ($handle !== false) {
41
            @fclose($handle);
Markus Sommer's avatar
Markus Sommer committed
42
            return true;
43 44
        }

Markus Sommer's avatar
Markus Sommer committed
45
        return false;
46 47 48 49 50 51
    }

    /**
     * Returns absolute path to given directory
     *
     * @param string $path Path to the file / directory
52
     * @param bool $create Create if not exists
53 54
     * @return string Absolute path
     */
Markus Sommer's avatar
Markus Sommer committed
55
    public static function getAbsoluteDirectory($path, $create = true)
56 57 58 59 60 61 62 63 64 65
    {
        if (empty($path)) {
            return PATH_site;
        }

        if (self::isAbsolutePath($path)) {
            $path = self::getRelativeDirectory($path);
        }

        if ($create && !self::fileExists(PATH_site . $path)) {
66
            \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep(PATH_site, $path);
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
        }

        return PATH_site . rtrim($path, '/') . '/';
    }

    /**
     * Returns absolute path to given directory
     *
     * @param string $path Path to the file / directory
     * @return string Relative path
     */
    public static function getRelativeDirectory($path)
    {
        if (empty($path)) {
            return '';
        }

        $path = str_replace(PATH_site, '', $path);
        if (is_dir($path)) {
            $path = rtrim($path, '/') . '/';
        }

        return $path;
    }

    /**
     * Returns the MD5 hash of a file
     *
     * @param string $filename Path to the file
     * @return string Generated hash or an empty string if file not found
     */
    public static function getFileHash($filename)
    {
        // Get md5 from local file
        if (self::isLocalUrl($filename)) {
            $filename = self::getAbsolutePathFromUrl($filename);
            return md5_file($filename);
        }

        // Get md5 from external file
107
        $contents = \TYPO3\CMS\Core\Utility\GeneralUtility::getURL($filename);
108 109 110 111 112 113 114 115 116 117 118
        if (!empty($contents)) {
            return md5($contents);
        }

        return '';
    }

    /**
     * Get last modification time of a file or directory
     *
     * @param string $filename Path to the file
119
     * @return int Timestamp of the modification time
120 121 122 123 124 125 126 127 128 129 130 131 132 133
     */
    public static function getModificationTime($filename)
    {
        // clearstatcache();
        return (int)@filemtime($filename);
    }

    /**
     * Transfers a file to client browser
     *
     * This function must be called before any HTTP headers have been sent
     *
     * @param string $filename Path to the file
     * @param string $visibleFileName Override real file name with this one for download
134
     * @return bool FALSE if file not exists
135 136 137 138 139 140 141 142 143
     */
    public static function transferFile($filename, $visibleFileName = '')
    {
        if (self::isLocalUrl($filename)) {
            $filename = self::getAbsolutePathFromUrl($filename);
        }

        // Check if file exists
        if (!self::fileExists($filename)) {
Markus Sommer's avatar
Markus Sommer committed
144
            return false;
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
        }

        // Get file name for download
        if (empty($visibleFileName)) {
            $visibleFileName = basename($filename);
        }

        // Send file
        header('Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0');
        header('Expires: Sat, 10 Jan 1970 00:00:00 GMT');
        header('Pragma: public');
        header('Content-Description: File Transfer');
        header('Content-Disposition: attachment; filename=' . (string)$visibleFileName);
        header('Content-type: x-application/octet-stream');
        header('Content-Transfer-Encoding: binary');
        if (self::isAbsolutePath($filename)) {
            header('Content-Length: ' . filesize($filename));
        }
        ob_clean();
        flush();
        readfile($filename);
        exit;
    }

    /**
     * Transfers file content to client browser
     *
     * This function must be called before any HTTP headers have been sent
     *
     * @param string $content File content
175
     * @param string $fileName File name for downloaded file
176
     * @return bool FALSE if something wents wrong
177 178 179 180
     */
    public static function transferFileContent($content, $fileName)
    {
        if (empty($content) || empty($fileName)) {
Markus Sommer's avatar
Markus Sommer committed
181
            return false;
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
        }

        // Send file content
        header('Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0');
        header('Expires: Sat, 10 Jan 1970 00:00:00 GMT');
        header('Pragma: public');
        header('Content-Description: File Transfer');
        header('Content-Disposition: attachment; filename=' . (string)$fileName);
        header('Content-type: x-application/octet-stream');
        header('Content-Transfer-Encoding: binary');
        header('Content-Length: ' . strlen($content));
        ob_clean();
        flush();
        echo $content;
        exit;
    }

    /**
     * Get a list of all files in a directory
     *
     * @param string $directory Path to the directory
     * @param string $fileType Type of the files to find
204 205
     * @param int $timestamp Timestamp of the last file change
     * @param bool $recursive Get subfolder content too
206 207
     * @return array All contained files
     */
Markus Sommer's avatar
Markus Sommer committed
208
    public static function getFiles($directory, $fileType = '', $timestamp = 0, $recursive = false)
209
    {
210
        $directory = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($directory);
211
        if (!self::fileExists($directory)) {
212
            return [];
213 214 215 216
        }

        $fileType = ltrim($fileType, '.');
        $timestamp = (int)$timestamp;
217
        $result = [];
218 219

        if ($recursive) {
220
            $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory));
221
        } else {
222
            $files = new \DirectoryIterator($directory);
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
        }

        foreach ($files as $file) {
            if ($file->isFile()) {
                $filename = $file->getPathname();

                // Check file type
                if ($fileType) {
                    if (substr($filename, strrpos($filename, '.') + 1) != $fileType) {
                        continue;
                    }
                }

                // Check timestamp
                if ($timestamp) {
                    $modificationTime = self::getModificationTime($filename);
                    if ($modificationTime < $timestamp) {
                        continue;
                    }
                }

                $result[] = $filename;
            }
        }

        return $result;
    }

    /**
     * Copy a file
     *
     * @param string $fromFileName Existing file
     * @param string $toFileName File name of the new file
256 257
     * @param bool $overwrite Existing A file with new name will be overwritten if set
     * @return bool TRUE if success
258
     */
Markus Sommer's avatar
Markus Sommer committed
259
    public static function copyFile($fromFileName, $toFileName, $overwrite = false)
260 261
    {
        if (empty($fromFileName) || empty($toFileName)) {
Markus Sommer's avatar
Markus Sommer committed
262
            return false;
263 264 265 266 267
        }

        // Check if file already exists
        $toFileExists = self::fileExists($toFileName);
        if ($toFileExists && !$overwrite) {
Markus Sommer's avatar
Markus Sommer committed
268
            return false;
269 270 271 272
        }

        // Check if target directory exists
        if (!self::fileExists(dirname($toFileName))) {
Markus Sommer's avatar
Markus Sommer committed
273
            return false;
274 275 276 277 278 279 280 281
        }

        // Get local url
        if (self::isLocalUrl($fromFileName)) {
            $fromFileName = self::getAbsolutePathFromUrl($fromFileName);
        }

        // Get file content
282
        $fromFile = \TYPO3\CMS\Core\Utility\GeneralUtility::getURL($fromFileName);
Markus Sommer's avatar
Markus Sommer committed
283 284
        if ($fromFile === false) {
            return false;
285 286 287 288 289 290 291 292
        }

        // Remove existing when successfully fetched new file
        if ($toFileExists) {
            self::removeFile($toFileName);
        }

        // Copy file to new name
293
        $result = \TYPO3\CMS\Core\Utility\GeneralUtility::writeFile($toFileName, $fromFile);
294

295
        return $result !== false;
296 297 298 299 300 301 302
    }

    /**
     * Copy a directory
     *
     * @param string $fromDirectory Existing directory
     * @param string $toDirectory Name of the new directory
303 304
     * @param bool $overwrite A directory with new name will be overwritten if set
     * @return bool TRUE if success
305
     */
Markus Sommer's avatar
Markus Sommer committed
306
    public static function copyDirectory($fromDirectory, $toDirectory, $overwrite = false)
307
    {
Markus Sommer's avatar
Markus Sommer committed
308
        $rollback = false;
309 310 311 312 313

        // Get directories
        $fromDirectory = rtrim(self::getAbsoluteDirectory($fromDirectory), '/');
        $toDirectory = self::getAbsoluteDirectory($toDirectory);
        $toDirectory .= substr($fromDirectory, strrpos($fromDirectory, '/') + 1);
Markus Sommer's avatar
Markus Sommer committed
314
        if (!self::fileExists($toDirectory) || $overwrite === true) {
315 316
            $toDirectory = self::getAbsoluteDirectory($toDirectory);
        } else {
Markus Sommer's avatar
Markus Sommer committed
317
            return false;
318 319 320
        }

        // Fetch directory content
321
        $elements = new \DirectoryIterator($fromDirectory);
322 323 324 325 326
        foreach ($elements as $element) {
            if ($element->isFile() || ($element->isDir() && !$element->isDot())) {
                $method = ($element->isFile() ? 'copyFile' : 'copyDirectory');
                $toName = $toDirectory . $element->getBasename();
                if (!self::$method($element->getPathname(), $toName, $overwrite)) {
Markus Sommer's avatar
Markus Sommer committed
327
                    $rollback = true;
328 329 330 331 332 333 334 335
                    break;
                }
            }
        }

        // Rollback
        if ($rollback) {
            self::removeDirectory($toDirectory);
Markus Sommer's avatar
Markus Sommer committed
336
            return false;
337 338
        }

Markus Sommer's avatar
Markus Sommer committed
339
        return true;
340 341 342 343 344 345 346
    }

    /**
     * Move a file
     *
     * @param string $fromFileName Existing file
     * @param string $toFileName File name of the new file
347 348
     * @param bool $overwrite A file with new name will be overwritten if set
     * @return bool TRUE if success
349
     */
Markus Sommer's avatar
Markus Sommer committed
350
    public static function moveFile($fromFileName, $toFileName, $overwrite = false)
351 352 353 354 355 356 357 358 359 360 361 362
    {
        $result = self::copyFile($fromFileName, $toFileName, $overwrite);
        if ($result && self::isAbsolutePath($fromFileName)) {
            self::removeFile($fromFileName);
        }
        return $result;
    }

    /**
     * Move a directory
     *
     * @param string $fromDirectory Existing directory
363
     * @param string $toDirectory Name of the new directory
364 365
     * @param bool $overwrite A directory with new name will be overwritten if set
     * @return bool TRUE if success
366
     */
Markus Sommer's avatar
Markus Sommer committed
367
    public static function moveDirectory($fromDirectory, $toDirectory, $overwrite = false)
368 369
    {
        if (!self::copyDirectory($fromDirectory, $toDirectory, $overwrite)) {
Markus Sommer's avatar
Markus Sommer committed
370
            return false;
371 372 373 374 375 376 377 378 379 380
        }
        return self::removeDirectory($fromDirectory);
    }

    /**
     * Move uploaded file to given directory
     *
     * @param string $tempname Temporary file name
     * @param string $filename Original file name
     * @param string $directory Directory path
381
     * @return string New file name
382
     */
Markus Sommer's avatar
Markus Sommer committed
383
    public static function moveUploadedFile($tempname, $filename, $directory = 'uploads/')
384
    {
385
        $basicFileFunctions = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Utility\File\BasicFileUtility::class);
386
        $newFilename = $basicFileFunctions->getUniqueName($filename, self::getAbsoluteDirectory($directory));
387
        if (\TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move($tempname, $newFilename)) {
388 389 390 391 392 393 394 395 396 397
            return basename($newFilename);
        }

        return '';
    }

    /**
     * Remove a file
     *
     * @param string $filename Path to the file
398
     * @return bool TRUE if success
399 400 401 402 403 404
     */
    public static function removeFile($filename)
    {
        if (self::fileExists($filename)) {
            return unlink($filename);
        }
Markus Sommer's avatar
Markus Sommer committed
405
        return true;
406 407 408 409 410 411
    }

    /**
     * Remove a directory and all contents
     *
     * @param string $directory Directory path
412 413
     * @param bool $removeNonEmpty Remove non empty directories
     * @return true if success
414
     */
Markus Sommer's avatar
Markus Sommer committed
415
    public static function removeDirectory($directory, $removeNonEmpty = true)
416
    {
417
        return \TYPO3\CMS\Core\Utility\GeneralUtility::rmdir($directory, (bool)$removeNonEmpty);
418 419 420 421 422 423
    }

    /**
     * Check if a URL is located to current server
     *
     * @param string $url UUrl to file
424
     * @return bool TRUE if given file is local
425 426 427
     */
    public static function isLocalUrl($url)
    {
428
        return \TYPO3\CMS\Core\Utility\GeneralUtility::isOnCurrentHost($url);
429 430 431 432 433 434
    }

    /**
     * Check if a filename is an absolute path in local file system
     *
     * @param string $path Path to file
435
     * @return bool TRUE if given path is absolute
436 437 438
     */
    public static function isAbsolutePath($path)
    {
439
        return strpos($path, PATH_site) === 0;
440 441 442 443 444 445 446 447 448 449
    }

    /**
     * Returns absolute path on local file system from an url
     *
     * @param string $url Url to file
     * @return string Absolute path to file
     */
    public static function getAbsolutePathFromUrl($url)
    {
450
        if (isset($GLOBALS['TSFE']->baseUrl) && $GLOBALS['TSFE']->baseUrl != '') {
451 452
            return PATH_site . str_ireplace($GLOBALS['TSFE']->baseUrl, '', $url);
        }
453
        $hostUrl = \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST') . '/';
454 455 456 457 458 459 460 461 462 463 464
        return PATH_site . str_ireplace($hostUrl, '', $url);
    }

    /**
     * Returns url from an absolute path on local file system
     *
     * @param string $path Absolute path to file
     * @return string Url to file
     */
    public static function getUrlFromAbsolutePath($path)
    {
465
        if (isset($GLOBALS['TSFE']->baseUrl) && $GLOBALS['TSFE']->baseUrl != '') {
466 467
            return PATH_site . str_ireplace($GLOBALS['TSFE']->baseUrl, '', $url);
        }
468
        $hostUrl = \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST') . '/';
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494

        return $hostUrl . str_replace(PATH_site, '', $path);
    }

    /**
     * Returns relative url from an absolute path on local file system
     *
     * @param string $path Absolute path to file
     * @return string Relative url to file
     */
    public static function getRelativeUrlFromAbsolutePath($path)
    {
        return str_replace(PATH_site, '/', $path);
    }

    /**
     * Compiles the ext_emconf.php file
     *
     * @param string $extKey Extension key
     * @param array $emConfArray Content of the file
     * @return string PHP file content, ready to write to ext_emconf.php file
     * @see tx_em_Extensions_Details::construct_ext_emconf_file()
     */
    public static function createExtEmconfFile($extKey, array $emConfArray)
    {
        $content = '<?php
495

496 497 498 499 500 501 502 503 504
/**
 * Extension Manager/Repository config file for ext "' . $extKey . '".
 *
 * Auto generated ' . date('d-m-Y H:i') . '
 *
 * Manual updates:
 * Only the data in the array - everything else is removed by next
 * writing. "version" and "dependencies" must not be touched!
 */
505

506
$EM_CONF[$_EXTKEY] = ' . self::arrayToCode($emConfArray, 0) . ';
507

508
';
509

510 511 512
        return str_replace(CR, '', $content);
    }

513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
    private static function arrayToCode($array, $level = 0)
    {
        $lines = 'array(' . LF;
        $level++;
        foreach ($array as $k => $v) {
            if (strlen($k) && is_array($v)) {
                $lines .= str_repeat(TAB, $level) . "'" . $k . "' => " . self::arrayToCode($v, $level);
            } elseif (strlen($k)) {
                $lines .= str_repeat(TAB, $level) . "'" . $k . "' => "
                    . (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($v) ? intval($v) : "'"
                    . \TYPO3\CMS\Core\Utility\GeneralUtility::slashJS(trim($v), 1) . "'") . ',' . LF;
            }
        }

        $lines .= str_repeat(TAB, $level - 1) . ')' . ($level - 1 == 0 ? '' : ',' . LF);
        return $lines;
    }

531 532 533 534 535 536 537 538
    /**
     * Returns information about uploaded file
     *
     * @param string $field Path to field (e.g. tx_myext_pi1.myObject.myAttribute)
     * @return array File information
     */
    public static function getFileInfo($field)
    {
Markus Sommer's avatar
Markus Sommer committed
539
        $arrayKeys = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode('.', $field, true);
540 541 542

        // No information found
        if (empty($_FILES[$arrayKeys[0]]['tmp_name'])) {
543
            return [];
544 545 546 547 548 549 550 551 552
        }

        // Single file structure
        if (is_string($_FILES[$arrayKeys[0]]['tmp_name'])) {
            return $_FILES[$arrayKeys[0]];
        }

        // Multi file structure
        if (is_array($_FILES[$arrayKeys[0]]['tmp_name'])) {
553
            $fileInfo = [];
554 555 556 557 558 559 560 561 562 563
            $fileArray = $_FILES[$arrayKeys[0]];
            array_shift($arrayKeys);

            foreach ($fileArray as $key => $values) {
                $info = $values;
                foreach ($arrayKeys as $arrayKey) {
                    if (isset($info[$arrayKey])) {
                        $info = $info[$arrayKey];
                    }
                }
Markus Sommer's avatar
Markus Sommer committed
564
                $fileInfo[$key] = (!is_array($info) ? $info : null);
565 566 567 568 569
            }

            return $fileInfo;
        }

570
        return [];
571 572
    }
}