Completed
Push — master ( d1a68a...39bb73 )
by Michael
01:32
created

Utility::rrmdir()   B

Complexity

Conditions 9
Paths 7

Size

Total Lines 29

Duplication

Lines 29
Ratio 100 %

Importance

Changes 0
Metric Value
cc 9
nc 7
nop 1
dl 29
loc 29
rs 8.0555
c 0
b 0
f 0
1
<?php
2
3
namespace XoopsModules\Xoopsfaq;
4
5
/*
6
 Xoopsfaq Utility Class Definition
7
8
 You may not change or alter any portion of this comment or credits of
9
 supporting developers from this source code or any supporting source code
10
 which is considered copyrighted (c) material of the original comment or credit
11
 authors.
12
13
 This program is distributed in the hope that it will be useful, but
14
 WITHOUT ANY WARRANTY; without even the implied warranty of
15
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16
 */
17
18
/**
19
 * Module:  myQuiz
20
 *
21
 * @package      ::    \module\xoopsfaq\class
22
 * @license      http://www.gnu.org/licenses/gpl-2.0.html GNU Public License
23
 * @copyright    http://xoops.org 2001-2017 &copy; XOOPS Project
24
 * @author       zyspec
25
 * @author       Mamba
26
 * @since        ::      File available since version 4.10
27
 */
28
29
use XoopsModules\Xoopsfaq;
30
31
/**
32
 * Xoopsfaq\Utility
33
 *
34
 * Static utility class to provide common functionality
35
 *
36
 */
37
class Utility
38
{
39
    use Common\VersionChecks; //checkVerXoops, checkVerPhp Traits
40
41
    use Common\ServerStats; // getServerStats Trait
42
43
    use Common\FilesManagement; // Files Management Trait
44
45
    /**
46
     *
47
     * Verifies XOOPS version meets minimum requirements for this module
48
     * @static
49
     * @param \XoopsModule $module
50
     *
51
     * @return bool true if meets requirements, false if not
52
     */
53
    public static function checkVerXoops($module)
54
    {
55
        $currentVersion  = strtolower(str_replace('XOOPS ', '', XOOPS_VERSION));
56
        $requiredVersion = strtolower($module->getInfo('min_xoops'));
57
        $vc              = version_compare($currentVersion, $requiredVersion);
58
        $success         = ($vc >= 0);
59
        if (false === $success) {
60
            xoops_loadLanguage('admin', $module->dirname());
61
            $module->setErrors(sprintf(_AM_XOOPSFAQ_ERROR_BAD_XOOPS, $requiredVersion, $currentVersion));
62
        }
63
64
        return $success;
65
    }
66
67
    /**
68
     *
69
     * Verifies PHP version meets minimum requirements for this module
70
     * @static
71
     * @param \XoopsModule $module
72
     *
73
     * @return bool true if meets requirements, false if not
74
     */
75
    public static function checkVerPHP($module)
76
    {
77
        xoops_loadLanguage('admin', $module->dirname());
78
        // check for minimum PHP version
79
        $success = true;
80
        $verNum  = PHP_VERSION;
81
        $reqVer  = $module->getInfo('min_php');
82
        if ((false !== $reqVer) && ('' !== $reqVer)) {
83
            if (version_compare($verNum, (string)$reqVer, '<')) {
84
                $module->setErrors(sprintf(_AM_XOOPSFAQ_ERROR_BAD_PHP, $reqVer, $verNum));
85
                $success = false;
86
            }
87
        }
88
        return $success;
89
    }
90
91
    /**
92
     *
93
     * Remove files and (sub)directories
94
     *
95
     * @param string $src source directory to delete
96
     *
97
     * @return bool true on success
98
     * @see \XoopsModules\Xoopsfaq\Helper::isUserAdmin()
99
     *
100
     * @see \XoopsModules\Xoopsfaq\Helper::getHelper()
101
     */
102 View Code Duplication
    public static function deleteDirectory($src)
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...
103
    {
104
        // Only continue if user is a 'global' Admin
105
        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...
106
            return false;
107
        }
108
109
        $success = true;
110
        // remove old files
111
        $dirInfo = new \SplFileInfo($src);
112
        // validate is a directory
113
        if ($dirInfo->isDir()) {
114
            $fileList = array_diff(scandir($src), ['..', '.']);
115
            foreach ($fileList as $k => $v) {
116
                $fileInfo = new \SplFileInfo($src . '/' . $v);
117
                if ($fileInfo->isDir()) {
118
                    // recursively handle subdirectories
119
                    if (!$success = static::deleteDirectory($fileInfo->getRealPath())) {
120
                        break;
121
                    }
122
                } elseif (!($success = unlink($fileInfo->getRealPath()))) {
123
                    break;
124
                }
125
            }
126
            // now delete this (sub)directory if all the files are gone
127
            if ($success) {
128
                $success = rmdir($dirInfo->getRealPath());
129
            }
130
        } else {
131
            // input is not a valid directory
132
            $success = false;
133
        }
134
        return $success;
135
    }
136
137
    /**
138
     *
139
     * Recursively remove directory
140
     *
141
     * @todo currently won't remove directories with hidden files, should it?
142
     *
143
     * @param string $src directory to remove (delete)
144
     *
145
     * @return bool true on success
146
     */
147 View Code Duplication
    public static function rrmdir($src)
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...
148
    {
149
        // Only continue if user is a 'global' Admin
150
        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...
151
            return false;
152
        }
153
154
        // If source is not a directory stop processing
155
        if (!is_dir($src)) {
156
            return false;
157
        }
158
159
        // Open the source directory to read in files
160
        $iterator = new \DirectoryIterator($src);
161
        foreach ($iterator as $fObj) {
162
            if ($fObj->isFile()) {
163
                $filename = $fObj->getPathname();
164
                $fObj     = null; // clear this iterator object to close the file
165
                if (!unlink($filename)) {
166
                    return false; // couldn't delete the file
167
                }
168
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
169
                // Try recursively on directory
170
                static::rrmdir($fObj->getPathname());
171
            }
172
        }
173
        $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...
174
        return rmdir($src); // remove the directory & return results
175
    }
176
177
    /**
178
     * Recursively move files from one directory to another
179
     *
180
     * @param String $src  - Source of files being moved
181
     * @param String $dest - Destination of files being moved
182
     *
183
     * @return bool true on success
184
     */
185 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...
186
    {
187
        // Only continue if user is a 'global' Admin
188
        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...
189
            return false;
190
        }
191
192
        // If source is not a directory stop processing
193
        if (!is_dir($src)) {
194
            return false;
195
        }
196
197
        // If the destination directory does not exist and could not be created stop processing
198
        if (!is_dir($dest) && !mkdir($dest, 0755)) {
199
            return false;
200
        }
201
202
        // Open the source directory to read in files
203
        $iterator = new \DirectoryIterator($src);
204
        foreach ($iterator as $fObj) {
205
            if ($fObj->isFile()) {
206
                rename($fObj->getPathname(), $dest . '/' . $fObj->getFilename());
207
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
208
                // Try recursively on directory
209
                static::rmove($fObj->getPathname(), $dest . '/' . $fObj->getFilename());
210
            }
211
        }
212
        $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...
213
        return rmdir($src); // remove the directory & return results
214
    }
215
216
    /**
217
     * Recursively copy directories and files from one directory to another
218
     *
219
     * @param string $src  - Source of files being moved
220
     * @param string $dest - Destination of files being moved
221
     *
222
     * @return bool true on success
223
     * @see \XoopsModules\Xoopsfaq\Helper::isUserAdmin()
224
     *
225
     * @see \XoopsModules\Xoopsfaq\Helper::getHelper()
226
     */
227 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...
228
    {
229
        // Only continue if user is a 'global' Admin
230
        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...
231
            return false;
232
        }
233
234
        // If source is not a directory stop processing
235
        if (!is_dir($src)) {
236
            return false;
237
        }
238
239
        // If the destination directory does not exist and could not be created stop processing
240
        if (!is_dir($dest) && !mkdir($dest, 0755)) {
241
            return false;
242
        }
243
244
        // Open the source directory to read in files
245
        $iterator = new \DirectoryIterator($src);
246
        foreach ($iterator as $fObj) {
247
            if ($fObj->isFile()) {
248
                copy($fObj->getPathname(), $dest . '/' . $fObj->getFilename());
249
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
250
                static::rcopy($fObj->getPathname(), $dest . '/' . $fObj->getFilename());
251
            }
252
        }
253
        return true;
254
    }
255
256
    /**
257
     * Render the icon links
258
     *
259
     * @param array $icon_array contains operation=>icon_name as key=>value
260
     * @param mixed $param      HTML parameter
261
     * @param mixed $value      HTML parameter value to set
262
     * @param mixed $extra      are any additional HTML attributes desired for the <a> tag
263
     * @return string
264
     */
265
    public static function renderIconLinks($icon_array = [], $param, $value = null, $extra = null)
266
    {
267
        $moduleDirName = basename(dirname(__DIR__));
268
        xoops_loadLanguage('admin', $moduleDirName);
269
        $ret = '';
270
        if (null !== $value) {
271
            foreach ($icon_array as $_op => $icon) {
272
                if (false === strpos($icon, '.')) {
273
                    $iconName = $icon;
274
                    $iconExt  = 'png';
275
                } else {
276
                    $iconName = substr($icon, 0, strlen($icon) - strrchr($icon, '.'));
277
                    $iconExt  = substr(strrchr($icon, '.'), 1);
278
                }
279
                $url = (!is_numeric($_op)) ? $_op . '?' . $param . '=' . $value : xoops_getenv('SCRIPT_NAME') . '?op=' . $iconName . '&amp;' . $param . '=' . $value;
280
                if (null !== $extra) {
281
                    $url .= ' ' . $extra;
282
                }
283
                $title = constant(htmlspecialchars(mb_strtoupper('_XO_LA_' . $iconName), ENT_QUOTES | ENT_HTML5));
284
                $img   = '<img src="' . \Xmf\Module\Admin::iconUrl($iconName . '.' . $iconExt, '16') . '"' . ' title ="' . $title . '"' . ' alt = "' . $title . '"' . ' class="bnone middle">';
285
                $ret   .= '<a href="' . $url . '"' . $extra . '>' . $img . '</a>';
286
            }
287
        }
288
        return $ret;
289
    }
290
}
291