Completed
Push — V6 ( 0a67f6...23eee8 )
by Georges
02:41
created

Directory::dirSize()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 4
eloc 8
c 3
b 1
f 0
nc 4
nop 2
dl 0
loc 16
rs 9.2
1
<?php
2
/**
3
 *
4
 * This file is part of phpFastCache.
5
 *
6
 * @license MIT License (MIT)
7
 *
8
 * For full copyright and license information, please see the docs/CREDITS.txt file.
9
 *
10
 * @author Khoa Bui (khoaofgod)  <[email protected]> http://www.phpfastcache.com
11
 * @author Georges.L (Geolim4)  <[email protected]>
12
 *
13
 */
14
namespace phpFastCache\Util;
15
16
use RecursiveDirectoryIterator;
17
use RecursiveIteratorIterator;
18
use SplFileInfo;
19
20
/**
21
 * Class Directory
22
 * @package phpFastCache\Util
23
 */
24
class Directory
25
{
26
    /**
27
     * Get the directory size
28
     * @param string $directory
29
     * @param bool $includeDirAllocSize
30
     * @return integer
31
     */
32
    public static function dirSize($directory, $includeDirAllocSize = false)
33
    {
34
        $size = 0;
35
        foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {
36
            /**
37
             * @var \SplFileInfo $file
38
             */
39
            if ($file->isFile()) {
40
                $size += filesize($file->getRealPath());
41
            } else if ($includeDirAllocSize) {
42
                $size += $file->getSize();
43
            }
44
        }
45
46
        return $size;
47
    }
48
49
    /**
50
     * @param string $path
51
     * @return int
52
     */
53
    public static function getFileCount($path)
54
    {
55
        $count = 0;
56
        $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::SELF_FIRST);
57
        foreach ($objects as $object) {
58
            /**
59
             * @var \SplFileInfo $object
60
             */
61
            if ($object->isFile()) {
62
                $count++;
63
            }
64
        }
65
66
        return $count;
67
    }
68
69
    /**
70
     * Recursively delete a directory and all of it's contents - e.g.the equivalent of `rm -r` on the command-line.
71
     * Consistent with `rmdir()` and `unlink()`, an E_WARNING level error will be generated on failure.
72
     *
73
     * @param string $source absolute path to directory or file to delete.
74
     * @param bool $removeOnlyChildren set to true will only remove content inside directory.
75
     *
76
     * @return bool true on success; false on failure
77
     */
78
    public static function rrmdir($source, $removeOnlyChildren = false)
79
    {
80
        if (empty($source) || file_exists($source) === false) {
81
            return false;
82
        }
83
84
        if (is_file($source) || is_link($source)) {
85
            return unlink($source);
0 ignored issues
show
Security File Manipulation introduced by
$source can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Fetching key HTTP_HOST from $_SERVER, and $_SERVER['HTTP_HOST'] is passed through str_replace(), and str_replace(':', '_', $_SERVER['HTTP_HOST']) is passed through strtolower(), and strtolower(str_replace(':', '_', $_SERVER['HTTP_HOST'])) is passed through preg_replace(), and $securityKey is assigned
    in src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 60
  2. Data is passed through trim(), and Data is passed through preg_replace()
    in vendor/src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 194
  3. $securityKey is assigned
    in src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 70
  4. $full_path is assigned
    in src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 87
  5. $full_path is passed through realpath()
    in src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 104
  6. PathSeekerTrait::getPath() returns tainted data, and $this->getPath(true) is passed to Directory::rrmdir()
    in src/phpFastCache/Drivers/Files/Driver.php on line 135

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
86
        }
87
88
        $files = new RecursiveIteratorIterator
89
        (
90
          new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
91
          RecursiveIteratorIterator::CHILD_FIRST
92
        );
93
94
        foreach ($files as $fileinfo) {
95
            /**
96
             * @var SplFileInfo $fileinfo
97
             */
98
            if ($fileinfo->isDir()) {
99
                if (self::rrmdir($fileinfo->getRealPath()) === false) {
100
                    return false;
101
                }
102
            } else if (unlink($fileinfo->getRealPath()) === false) {
103
                return false;
104
            }
105
        }
106
107
        if ($removeOnlyChildren === false) {
108
            return rmdir($source);
0 ignored issues
show
Security File Manipulation introduced by
$source can contain request data and is used in file manipulation context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Fetching key HTTP_HOST from $_SERVER, and $_SERVER['HTTP_HOST'] is passed through str_replace(), and str_replace(':', '_', $_SERVER['HTTP_HOST']) is passed through strtolower(), and strtolower(str_replace(':', '_', $_SERVER['HTTP_HOST'])) is passed through preg_replace(), and $securityKey is assigned
    in src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 60
  2. Data is passed through trim(), and Data is passed through preg_replace()
    in vendor/src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 194
  3. $securityKey is assigned
    in src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 70
  4. $full_path is assigned
    in src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 87
  5. $full_path is passed through realpath()
    in src/phpFastCache/Core/Pool/IO/PathSeekerTrait.php on line 104
  6. PathSeekerTrait::getPath() returns tainted data, and $this->getPath(true) is passed to Directory::rrmdir()
    in src/phpFastCache/Drivers/Files/Driver.php on line 135

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
109
        }
110
111
        return true;
112
    }
113
114
    /**
115
     * Alias of realpath() but work
116
     * on non-existing files
117
     *
118
     * @param $path
119
     * @return string
120
     */
121
    public static function getAbsolutePath($path)
122
    {
123
        $path = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path);
124
        $parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
125
        $absolutes = [];
126
        foreach ($parts as $part) {
127
            if ('.' === $part) {
128
                continue;
129
            }
130
            if ('..' === $part) {
131
                array_pop($absolutes);
132
            } else {
133
                $absolutes[] = $part;
134
            }
135
        }
136
137
        return implode(DIRECTORY_SEPARATOR, $absolutes);
138
    }
139
}