FilesManagement::copyFile()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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