Completed
Push — master ( 76d541...123636 )
by Michael
10s
created

XsitemapUtility::deleteDirectory()   D

Complexity

Conditions 9
Paths 12

Size

Total Lines 37
Code Lines 20

Duplication

Lines 3
Ratio 8.11 %

Importance

Changes 0
Metric Value
cc 9
eloc 20
nc 12
nop 1
dl 3
loc 37
rs 4.909
c 0
b 0
f 0
1
<?php
2
/*
3
 Xsitemap Utility Class Definition
4
5
 You may not change or alter any portion of this comment or credits of
6
 supporting developers from this source code or any supporting source code
7
 which is considered copyrighted (c) material of the original comment or credit
8
 authors.
9
10
 This program is distributed in the hope that it will be useful, but
11
 WITHOUT ANY WARRANTY; without even the implied warranty of
12
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
 */
14
/**
15
 * Module:  xSitemap
16
 *
17
 * @package      \module\xsitemap\class
18
 * @license      http://www.fsf.org/copyleft/gpl.html GNU public license
19
 * @copyright    http://xoops.org 2001-2017 &copy; XOOPS Project
20
 * @author       ZySpec <[email protected]>
21
 * @author       Mamba <[email protected]>
22
 * @since        File available since version 1.54
23
 */
24
25
/**
26
 * XsitemapUtility
27
 *
28
 * Static utility class to provide common functionality
29
 *
30
 */
31
class XsitemapUtility extends XoopsObject
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
32
{
33
    /**
34
     *
35
     * Verifies XOOPS version meets minimum requirements for this module
36
     * @static
37
     * @param XoopsModule $module
38
     *
39
     * @return bool true if meets requirements, false if not
40
     */
41
    public static function checkVerXoops(XoopsModule $module)
42
    {
43
        xoops_loadLanguage('admin', $module->dirname());
44
        //check for minimum XOOPS version
45
        $currentVer  = substr(XOOPS_VERSION, 6); // get the numeric part of string
46
        $currArray   = explode('.', $currentVer);
47
        $requiredVer = '' . $module->getInfo('min_xoops'); //making sure it's a string
48
        $reqArray    = explode('.', $requiredVer);
49
        $success     = true;
50
        foreach ($reqArray as $k => $v) {
51
            if (isset($currArray[$k])) {
52
                if ($currArray[$k] > $v) {
53
                    break;
54
                } elseif ($currArray[$k] == $v) {
55
                    continue;
56
                } else {
57
                    $success = false;
58
                    break;
59
                }
60
            } else {
61
                if ((int)$v > 0) { // handles versions like x.x.x.0_RC2
62
                    $success = false;
63
                    break;
64
                }
65
            }
66
        }
67
68
        if (false === $success) {
69
            $module->setErrors(sprintf(_AM_XSITEMAP_ERROR_BAD_XOOPS, $requiredVer, $currentVer));
70
        }
71
72
        return $success;
73
    }
74
75
    /**
76
     *
77
     * Verifies PHP version meets minimum requirements for this module
78
     * @static
79
     * @param XoopsModule $module
80
     *
81
     * @return bool true if meets requirements, false if not
82
     */
83
    public static function checkVerPhp(XoopsModule $module)
84
    {
85
        xoops_loadLanguage('admin', $module->dirname());
86
        // check for minimum PHP version
87
        $success = true;
88
        $verNum  = PHP_VERSION;
89
        $reqVer  =& $module->getInfo('min_php');
90
        if ((false !== $reqVer) && ('' !== $reqVer)) {
91
            if (version_compare($verNum, (string)$reqVer, '<')) {
92
                $module->setErrors(sprintf(_AM_XSITEMAP_ERROR_BAD_PHP, $reqVer, $verNum));
93
                $success = false;
94
            }
95
        }
96
97
        return $success;
98
    }
99
100
    /**
101
     *
102
     * Remove files and (sub)directories
103
     *
104
     * @param string $src source directory to delete
105
     *
106
     * @uses \Xmf\Module\Helper::getHelper()
107
     * @uses \Xmf\Module\Helper::isUserAdmin()
108
     *
109
     * @return bool true on success
110
     */
111
    public static function deleteDirectory($src)
0 ignored issues
show
Coding Style introduced by
deleteDirectory uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
112
    {
113
        // Only continue if user is a 'global' Admin
114 View Code Duplication
        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...
Duplication introduced by
This code seems to be duplicated across 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...
115
            return false;
116
        }
117
118
        $success = true;
119
        // remove old files
120
        $dirInfo = new SplFileInfo($src);
121
        // validate is a directory
122
        if ($dirInfo->isDir()) {
123
            $fileList = array_diff(scandir($src), array('..', '.'));
124
            foreach ($fileList as $k => $v) {
125
                $fileInfo = new SplFileInfo("{$src}/{$v}");
126
                if ($fileInfo->isDir()) {
127
                    // recursively handle subdirectories
128
                    if (!$success = self::deleteDirectory($fileInfo->getRealPath())) {
129
                        break;
130
                    }
131
                } else {
132
                    // delete the file
133
                    if (!($success = unlink($fileInfo->getRealPath()))) {
134
                        break;
135
                    }
136
                }
137
            }
138
            // now delete this (sub)directory if all the files are gone
139
            if ($success) {
140
                $success = rmdir($dirInfo->getRealPath());
141
            }
142
        } else {
143
            // input is not a valid directory
144
            $success = false;
145
        }
146
        return $success;
147
    }
148
149
    /**
150
     *
151
     * Recursively remove directory
152
     *
153
     * @todo currently won't remove directories with hidden files, should it?
154
     *
155
     * @param string $src directory to remove (delete)
156
     *
157
     * @return bool true on success
158
     */
159
    public static function rrmdir($src)
0 ignored issues
show
Coding Style introduced by
rrmdir uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
160
    {
161
        // Only continue if user is a 'global' Admin
162 View Code Duplication
        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...
Duplication introduced by
This code seems to be duplicated across 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...
163
            return false;
164
        }
165
166
        // If source is not a directory stop processing
167
        if (!is_dir($src)) {
168
            return false;
169
        }
170
171
        $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...
172
173
        // Open the source directory to read in files
174
        $iterator = new DirectoryIterator($src);
175
        foreach ($iterator as $fObj) {
176
            if ($fObj->isFile()) {
177
                $filename = $fObj->getPathname();
178
                $fObj     = null; // clear this iterator object to close the file
179
                if (!unlink($filename)) {
180
                    return false; // couldn't delete the file
181
                }
182
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
183
                // Try recursively on directory
184
                self::rrmdir($fObj->getPathname());
185
            }
186
        }
187
        $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...
188
        return rmdir($src); // remove the directory & return results
189
    }
190
191
    /**
192
     * Recursively move files from one directory to another
193
     *
194
     * @param string $src  - Source of files being moved
195
     * @param string $dest - Destination of files being moved
196
     *
197
     * @return bool true on success
198
     */
199
    public static function rmove($src, $dest)
0 ignored issues
show
Coding Style introduced by
rmove uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
200
    {
201
        // Only continue if user is a 'global' Admin
202 View Code Duplication
        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...
Duplication introduced by
This code seems to be duplicated across 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...
203
            return false;
204
        }
205
206
        // If source is not a directory stop processing
207
        if (!is_dir($src)) {
208
            return false;
209
        }
210
211
        // If the destination directory does not exist and could not be created stop processing
212
        if (!is_dir($dest) && !mkdir($dest, 0755)) {
213
            return false;
214
        }
215
216
        // Open the source directory to read in files
217
        $iterator = new DirectoryIterator($src);
218 View Code Duplication
        foreach ($iterator as $fObj) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
219
            if ($fObj->isFile()) {
220
                rename($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
221
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
222
                // Try recursively on directory
223
                self::rmove($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
224
                //                rmdir($fObj->getPath()); // now delete the directory
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
225
            }
226
        }
227
        $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...
228
        return rmdir($src); // remove the directory & return results
229
    }
230
231
    /**
232
     * Recursively copy directories and files from one directory to another
233
     *
234
     * @param string $src  - Source of files being moved
235
     * @param string $dest - Destination of files being moved
236
     *
237
     * @uses \Xmf\Module\Helper::getHelper()
238
     * @uses \Xmf\Module\Helper::isUserAdmin()
239
     *
240
     * @return bool true on success
241
     */
242
    public static function rcopy($src, $dest)
0 ignored issues
show
Coding Style introduced by
rcopy uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
243
    {
244
        // Only continue if user is a 'global' Admin
245 View Code Duplication
        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...
Duplication introduced by
This code seems to be duplicated across 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...
246
            return false;
247
        }
248
249
        // If source is not a directory stop processing
250
        if (!is_dir($src)) {
251
            return false;
252
        }
253
254
        // If the destination directory does not exist and could not be created stop processing
255
        if (!is_dir($dest) && !mkdir($dest, 0755)) {
256
            return false;
257
        }
258
259
        // Open the source directory to read in files
260
        $iterator = new DirectoryIterator($src);
261 View Code Duplication
        foreach ($iterator as $fObj) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
262
            if ($fObj->isFile()) {
263
                copy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
264
            } else if (!$fObj->isDot() && $fObj->isDir()) {
265
                self::rcopy($fObj->getPathname(), "{$dest}/" . $fObj - getFilename());
266
            }
267
        }
268
        return true;
269
    }
270
}
271