FilesManagement::deleteDirectory()   B
last analyzed

Complexity

Conditions 9
Paths 12

Size

Total Lines 34
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 18
c 0
b 0
f 0
dl 0
loc 34
rs 8.0555
cc 9
nc 12
nop 1
1
<?php declare(strict_types=1);
2
3
namespace XoopsModules\Xoopsheadline\Common;
4
5
/*
6
 You may not change or alter any portion of this comment or credits
7
 of supporting developers from this source code or any supporting source code
8
 which is considered copyrighted (c) material of the original comment or credit authors.
9
10
 This program is distributed in the hope that it will be useful,
11
 but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
 */
14
15
/**
16
 * @copyright   XOOPS Project (https://xoops.org)
17
 * @license     https://www.fsf.org/copyleft/gpl.html GNU public license
18
 * @author      mamba <[email protected]>
19
 */
20
trait FilesManagement
21
{
22
    /**
23
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
24
     *
25
     * @param string $folder The full path of the directory to check
26
     */
27
    public static function createFolder(string $folder): void
28
    {
29
        try {
30
            if (!\is_dir($folder)) {
31
                if (!\is_dir($folder) && !\mkdir($folder) && !\is_dir($folder)) {
32
                    throw new \RuntimeException(\sprintf('Unable to create the %s directory', $folder));
33
                }
34
35
                file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
36
            }
37
        } catch (\Exception $e) {
38
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br>';
39
        }
40
    }
41
42
    public static function copyFile(string $file, string $folder): bool
43
    {
44
        return \copy($file, $folder);
45
    }
46
47
    public static function recurseCopy(string $src, string $dst): void
48
    {
49
        $dir = \opendir($src);
50
        //        @mkdir($dst);
51
        if (!@\mkdir($dst) && !\is_dir($dst)) {
52
            throw new \RuntimeException('The directory ' . $dst . ' could not be created.');
53
        }
54
        while (false !== ($file = \readdir($dir))) {
55
            if (('.' !== $file) && ('..' !== $file)) {
56
                if (\is_dir($src . '/' . $file)) {
57
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
58
                } else {
59
                    \copy($src . '/' . $file, $dst . '/' . $file);
60
                }
61
            }
62
        }
63
        \closedir($dir);
64
    }
65
66
    /**
67
     * Copy a file, or recursively copy a folder and its contents
68
     * @param string $source Source path
69
     * @param string $dest   Destination path
70
     * @return      bool     Returns true on success, false on failure
71
     * @author      Aidan Lister <[email protected]>
72
     * @version     1.0.1
73
     * @link        https://aidanlister.com/2004/04/recursively-copying-directories-in-php/
74
     */
75
    public static function xcopy(string $source, string $dest): bool
76
    {
77
        // Check for symlinks
78
        if (\is_link($source)) {
79
            return \symlink(\readlink($source), $dest);
80
        }
81
82
        // Simple copy for a file
83
        if (\is_file($source)) {
84
            return \copy($source, $dest);
85
        }
86
87
        // Make destination directory
88
        if (!\is_dir($dest) && (!\mkdir($dest) && !\is_dir($dest))) {
89
            throw new \RuntimeException(\sprintf('Directory "%s" was not created', $dest));
90
        }
91
92
        // Loop through the folder
93
        $dir = \dir($source);
94
        if (@\is_dir((string)$dir)) {
95
            while (false !== ($entry = $dir->read())) {
96
                // Skip pointers
97
                if ('.' === $entry || '..' === $entry) {
98
                    continue;
99
                }
100
                // Deep copy directories
101
                self::xcopy("${source}/${entry}", "${dest}/${entry}");
102
            }
103
            // Clean up
104
            $dir->close();
105
        }
106
107
        return true;
108
    }
109
110
    /**
111
     * Remove files and (sub)directories
112
     *
113
     * @param string $src source directory to delete
114
     *
115
     * @return bool true on success
116
     * @uses \Xmf\Module\Helper::isUserAdmin()
117
     *
118
     * @uses \Xmf\Module\Helper::getHelper()
119
     */
120
    public static function deleteDirectory(string $src): bool
121
    {
122
        // Only continue if user is a 'global' Admin
123
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
124
            return false;
125
        }
126
127
        $success = true;
128
        // remove old files
129
        $dirInfo = new \SplFileInfo($src);
130
        // validate is a directory
131
        if ($dirInfo->isDir()) {
132
            $fileList = \array_diff(\scandir($src, \SCANDIR_SORT_NONE), ['..', '.']);
133
            foreach ($fileList as $k => $v) {
134
                $fileInfo = new \SplFileInfo("{$src}/{$v}");
135
                if ($fileInfo->isDir()) {
136
                    // recursively handle subdirectories
137
                    if (!$success = self::deleteDirectory($fileInfo->getRealPath())) {
138
                        break;
139
                    }
140
                } elseif (!($success = \unlink($fileInfo->getRealPath()))) {
141
                    break;
142
                }
143
            }
144
            // now delete this (sub)directory if all the files are gone
145
            if ($success) {
146
                $success = \rmdir($dirInfo->getRealPath());
147
            }
148
        } else {
149
            // input is not a valid directory
150
            $success = false;
151
        }
152
153
        return $success;
154
    }
155
156
    /**
157
     * Recursively remove directory
158
     *
159
     * @todo currently won't remove directories with hidden files, should it?
160
     *
161
     * @param string $src directory to remove (delete)
162
     *
163
     * @return bool true on success
164
     */
165
    public static function rrmdir(string $src): bool
166
    {
167
        // Only continue if user is a 'global' Admin
168
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
169
            return false;
170
        }
171
172
        // If source is not a directory stop processing
173
        if (!\is_dir($src)) {
174
            return false;
175
        }
176
177
        $success = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $success is dead and can be removed.
Loading history...
178
179
        // Open the source directory to read in files
180
        $iterator = new \DirectoryIterator($src);
181
        foreach ($iterator as $fObj) {
182
            if ($fObj->isFile()) {
183
                $filename = $fObj->getPathname();
184
                $fObj     = null; // clear this iterator object to close the file
0 ignored issues
show
Unused Code introduced by
The assignment to $fObj is dead and can be removed.
Loading history...
185
                if (!\unlink($filename)) {
186
                    return false; // couldn't delete the file
187
                }
188
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
189
                // Try recursively on directory
190
                self::rrmdir($fObj->getPathname());
191
            }
192
        }
193
        $iterator = null;   // clear iterator Obj to close file/directory
0 ignored issues
show
Unused Code introduced by
The assignment to $iterator is dead and can be removed.
Loading history...
194
195
        return \rmdir($src); // remove the directory & return results
196
    }
197
198
    /**
199
     * Recursively move files from one directory to another
200
     *
201
     * @param string $src  - Source of files being moved
202
     * @param string $dest - Destination of files being moved
203
     *
204
     * @return bool true on success
205
     */
206
    public static function rmove(string $src, string $dest): bool
207
    {
208
        // Only continue if user is a 'global' Admin
209
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
210
            return false;
211
        }
212
213
        // If source is not a directory stop processing
214
        if (!\is_dir($src)) {
215
            return false;
216
        }
217
218
        // If the destination directory does not exist and could not be created stop processing
219
        if (!\is_dir($dest) && !\mkdir($dest) && !\is_dir($dest)) {
220
            return false;
221
        }
222
223
        // Open the source directory to read in files
224
        $iterator = new \DirectoryIterator($src);
225
        foreach ($iterator as $fObj) {
226
            if ($fObj->isFile()) {
227
                \rename($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
228
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
229
                // Try recursively on directory
230
                self::rmove($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
231
                //                rmdir($fObj->getPath()); // now delete the directory
232
            }
233
        }
234
        $iterator = null;   // clear iterator Obj to close file/directory
0 ignored issues
show
Unused Code introduced by
The assignment to $iterator is dead and can be removed.
Loading history...
235
236
        return \rmdir($src); // remove the directory & return results
237
    }
238
239
    /**
240
     * Recursively copy directories and files from one directory to another
241
     *
242
     * @param string $src  - Source of files being moved
243
     * @param string $dest - Destination of files being moved
244
     *
245
     * @return bool true on success
246
     * @uses \Xmf\Module\Helper::isUserAdmin()
247
     *
248
     * @uses \Xmf\Module\Helper::getHelper()
249
     */
250
    public static function rcopy(string $src, string $dest): bool
251
    {
252
        // Only continue if user is a 'global' Admin
253
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
254
            return false;
255
        }
256
257
        // If source is not a directory stop processing
258
        if (!\is_dir($src)) {
259
            return false;
260
        }
261
262
        // If the destination directory does not exist and could not be created stop processing
263
        if (!\is_dir($dest) && !\mkdir($dest) && !\is_dir($dest)) {
264
            return false;
265
        }
266
267
        // Open the source directory to read in files
268
        $iterator = new \DirectoryIterator($src);
269
        foreach ($iterator as $fObj) {
270
            if ($fObj->isFile()) {
271
                \copy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
272
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
273
                self::rcopy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
274
            }
275
        }
276
277
        return true;
278
    }
279
}
280