FilesManagement::xcopy()   B
last analyzed

Complexity

Conditions 8
Paths 6

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
nc 6
nop 2
dl 0
loc 33
rs 8.1475
c 0
b 0
f 0
1
<?php namespace Xoopsmodules\randomquote\common;
2
3
/*
4
 You may not change or alter any portion of this comment or credits
5
 of supporting developers from this source code or any supporting source code
6
 which is considered copyrighted (c) material of the original comment or credit authors.
7
8
 This program is distributed in the hope that it will be useful,
9
 but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
*/
12
/**
13
 * Module: randomquote
14
 *
15
 * @category        Module
16
 * @package         randomquote
17
 * @author          XOOPS Development Team <[email protected]> - <https://xoops.org>
18
 * @copyright       {@link https://xoops.org/ XOOPS Project}
19
 * @license         GPL 2.0 or later
20
 * @link            https://xoops.org/
21
 * @since           1.0.0
22
 */
23
trait FilesManagement
24
{
25
    /**
26
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
27
     *
28
     * @param string $folder The full path of the directory to check
29
     *
30
     * @return void
31
     * @throws \RuntimeException
32
     */
33
    public static function createFolder($folder)
34
    {
35
        try {
36
            if (!file_exists($folder)) {
37
                if (!mkdir($folder) && !is_dir($folder)) {
38
                    throw new \RuntimeException(sprintf('Unable to create the %s directory', $folder));
39
                }
40
41
                file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
42
            }
43
        }
44
        catch (\Exception $e) {
45
            echo 'Caught exception: ', $e->getMessage(), '<br>';
46
        }
47
    }
48
49
    /**
50
     * @param $file
51
     * @param $folder
52
     * @return bool
53
     */
54
    public static function copyFile($file, $folder)
55
    {
56
        return copy($file, $folder);
57
    }
58
59
    /**
60
     * @param $src
61
     * @param $dst
62
     */
63
    public static function recurseCopy($src, $dst)
64
    {
65
        $dir = opendir($src);
66
        @mkdir($dst);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
67
        while (false !== ($file = readdir($dir))) {
68
            if (('.' !== $file) && ('..' !== $file)) {
69
                if (is_dir($src . '/' . $file)) {
70
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
71
                } else {
72
                    copy($src . '/' . $file, $dst . '/' . $file);
73
                }
74
            }
75
        }
76
        closedir($dir);
77
    }
78
79
    /**
80
     * Copy a file, or recursively copy a folder and its contents
81
     * @author      Aidan Lister <[email protected]>
82
     * @version     1.0.1
83
     * @link        http://aidanlister.com/2004/04/recursively-copying-directories-in-php/
84
     * @param       string $source Source path
85
     * @param       string $dest   Destination path
86
     * @return      bool     Returns true on success, false on failure
87
     */
88
    public static function xcopy($source, $dest)
89
    {
90
        // Check for symlinks
91
        if (is_link($source)) {
92
            return symlink(readlink($source), $dest);
93
        }
94
95
        // Simple copy for a file
96
        if (is_file($source)) {
97
            return copy($source, $dest);
98
        }
99
100
        // Make destination directory
101
        if (!is_dir($dest)) {
102
            mkdir($dest);
103
        }
104
105
        // Loop through the folder
106
        $dir = dir($source);
107
        if (@is_dir($dir)) {
108
            while (false !== $entry = $dir->read()) {
109
                // Skip pointers
110
                if ('.' === $entry || '..' === $entry) {
111
                    continue;
112
                }
113
                // Deep copy directories
114
                self::xcopy("$source/$entry", "$dest/$entry");
115
            }
116
            // Clean up
117
            $dir->close();
118
        }
119
        return true;
120
    }
121
122
    /**
123
     *
124
     * Remove files and (sub)directories
125
     *
126
     * @param string $src source directory to delete
127
     *
128
     * @uses \Xmf\Module\Helper::getHelper()
129
     * @uses \Xmf\Module\Helper::isUserAdmin()
130
     *
131
     * @return bool true on success
132
     */
133
    public static function deleteDirectory($src)
134
    {
135
        // Only continue if user is a 'global' Admin
136
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
0 ignored issues
show
Bug introduced by
The class XoopsUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
137
            return false;
138
        }
139
140
        $success = true;
141
        // remove old files
142
        $dirInfo = new \SplFileInfo($src);
143
        // validate is a directory
144
        if ($dirInfo->isDir()) {
145
            $fileList = array_diff(scandir($src, SCANDIR_SORT_NONE), ['..', '.']);
146
            foreach ($fileList as $k => $v) {
147
                $fileInfo = new \SplFileInfo("{$src}/{$v}");
148
                if ($fileInfo->isDir()) {
149
                    // recursively handle subdirectories
150
                    if (!$success = self::deleteDirectory($fileInfo->getRealPath())) {
151
                        break;
152
                    }
153
                } else {
154
                    // delete the file
155
                    if (!($success = unlink($fileInfo->getRealPath()))) {
156
                        break;
157
                    }
158
                }
159
            }
160
            // now delete this (sub)directory if all the files are gone
161
            if ($success) {
162
                $success = rmdir($dirInfo->getRealPath());
163
            }
164
        } else {
165
            // input is not a valid directory
166
            $success = false;
167
        }
168
        return $success;
169
    }
170
171
    /**
172
     *
173
     * Recursively remove directory
174
     *
175
     * @todo currently won't remove directories with hidden files, should it?
176
     *
177
     * @param string $src directory to remove (delete)
178
     *
179
     * @return bool true on success
180
     */
181
    public static function rrmdir($src)
182
    {
183
        // Only continue if user is a 'global' Admin
184
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
0 ignored issues
show
Bug introduced by
The class XoopsUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
185
            return false;
186
        }
187
188
        // If source is not a directory stop processing
189
        if (!is_dir($src)) {
190
            return false;
191
        }
192
193
        $success = true;
0 ignored issues
show
Unused Code introduced by
$success is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
194
195
        // Open the source directory to read in files
196
        $iterator = new \DirectoryIterator($src);
197
        foreach ($iterator as $fObj) {
198
            if ($fObj->isFile()) {
199
                $filename = $fObj->getPathname();
200
                $fObj     = null; // clear this iterator object to close the file
201
                if (!unlink($filename)) {
202
                    return false; // couldn't delete the file
203
                }
204
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
205
                // Try recursively on directory
206
                self::rrmdir($fObj->getPathname());
207
            }
208
        }
209
        $iterator = null;   // clear iterator Obj to close file/directory
0 ignored issues
show
Unused Code introduced by
$iterator is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
210
        return rmdir($src); // remove the directory & return results
211
    }
212
213
    /**
214
     * Recursively move files from one directory to another
215
     *
216
     * @param string $src  - Source of files being moved
217
     * @param string $dest - Destination of files being moved
218
     *
219
     * @return bool true on success
220
     */
221 View Code Duplication
    public static function rmove($src, $dest)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
222
    {
223
        // Only continue if user is a 'global' Admin
224
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
0 ignored issues
show
Bug introduced by
The class XoopsUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
225
            return false;
226
        }
227
228
        // If source is not a directory stop processing
229
        if (!is_dir($src)) {
230
            return false;
231
        }
232
233
        // If the destination directory does not exist and could not be created stop processing
234
        if (!is_dir($dest) && !mkdir($dest, 0755)) {
235
            return false;
236
        }
237
238
        // Open the source directory to read in files
239
        $iterator = new \DirectoryIterator($src);
240
        foreach ($iterator as $fObj) {
241
            if ($fObj->isFile()) {
242
                rename($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
243
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
244
                // Try recursively on directory
245
                self::rmove($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
246
                //                rmdir($fObj->getPath()); // now delete the directory
247
            }
248
        }
249
        $iterator = null;   // clear iterator Obj to close file/directory
0 ignored issues
show
Unused Code introduced by
$iterator is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
250
        return rmdir($src); // remove the directory & return results
251
    }
252
253
    /**
254
     * Recursively copy directories and files from one directory to another
255
     *
256
     * @param string $src  - Source of files being moved
257
     * @param string $dest - Destination of files being moved
258
     *
259
     * @uses \Xmf\Module\Helper::getHelper()
260
     * @uses \Xmf\Module\Helper::isUserAdmin()
261
     *
262
     * @return bool true on success
263
     */
264 View Code Duplication
    public static function rcopy($src, $dest)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
265
    {
266
        // Only continue if user is a 'global' Admin
267
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
0 ignored issues
show
Bug introduced by
The class XoopsUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
268
            return false;
269
        }
270
271
        // If source is not a directory stop processing
272
        if (!is_dir($src)) {
273
            return false;
274
        }
275
276
        // If the destination directory does not exist and could not be created stop processing
277
        if (!is_dir($dest) && !mkdir($dest, 0755)) {
278
            return false;
279
        }
280
281
        // Open the source directory to read in files
282
        $iterator = new \DirectoryIterator($src);
283
        foreach ($iterator as $fObj) {
284
            if ($fObj->isFile()) {
285
                copy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
286
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
287
                self::rcopy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
288
            }
289
        }
290
        return true;
291
    }
292
}
293