Completed
Push — master ( d2eaaf...4c5bd9 )
by Michael
02:35 queued 01:13
created

action.module.php ➔ xoops_module_pre_install_xsitemap()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 13
Code Lines 11

Duplication

Lines 13
Ratio 100 %

Importance

Changes 0
Metric Value
cc 5
eloc 11
nc 4
nop 1
dl 13
loc 13
rs 8.8571
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 44 and the first side effect is on line 33.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/*
3
 You may not change or alter any portion of this comment or credits
4
 of supporting developers from this source code or any supporting source code
5
 which is considered copyrighted (c) material of the original comment or credit authors.
6
7
 This program is distributed in the hope that it will be useful,
8
 but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
*/
11
/**
12
 * Module: xsitemap
13
 *
14
 * @package    module\xsitemap\includes
15
 * @author     Taiwen Jiang <[email protected]>
16
 * @author     ZySpec <[email protected]>
17
 * @copyright  https://xoops.org 2001-2017 XOOPS Project
18
 * @license    http://www.fsf.org/copyleft/gpl.html GNU public license
19
 * @link       https://xoops.org XOOPS
20
 * @since      1.00
21
 */
22
23
use \Xoopsmodules\xsitemap;
24
25
/**
26
 * @internal {Make sure you PROTECT THIS FILE}
27
 */
28
29 View Code Duplication
if ((!defined('XOOPS_ROOT_PATH'))
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...
30
    || !($GLOBALS['xoopsUser'] instanceof XoopsUser)
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...
31
    || !$GLOBALS['xoopsUser']->isAdmin()
32
) {
33
    exit('Restricted access' . PHP_EOL);
34
}
35
36
/**
37
 *
38
 * Prepares system prior to attempting to install module
39
 *
40
 * @param XoopsModule $module
41
 *
42
 * @return bool true if ready to install, false if not
43
 */
44 View Code Duplication
function xoops_module_pre_install_xsitemap(XoopsModule $module)
0 ignored issues
show
Duplication introduced by
This function 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...
45
{
46
    $moduleDirName = basename(dirname(__DIR__));
47
    /** @var Utility $utilityClass */
48
    $utilityClass    = xsitemap\Utility;
49
    if (!class_exists($utilityClass)) {
50
        xoops_load('utility', $moduleDirName);
51
    }
52
53
    $xoopsSuccess = $utilityClass::checkVerXoops($module);
54
    $phpSuccess   = $utilityClass::checkVerPhp($module);
55
    return $xoopsSuccess && $phpSuccess;
56
}
57
58
/**
59
 *
60
 * Performs tasks required during installation of the module
61
 *
62
 * @param XoopsModule $module
63
 *
64
 * @return bool true if installation successful, false if not
65
 */
66
function xoops_module_install_xsitemap(XoopsModule $module)
0 ignored issues
show
Unused Code introduced by
The parameter $module is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
67
{
68
    return true; //
69
    /** @internal following code removed, it will fail because module not fully loaded/available until
70
     * after install, module now uses XOOPS preload instead */
71
    /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
51% 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...
72
    //28/08/2009 by urbanspaceman
73
    include_once $GLOBALS['xoops']->path("class/tree.php");
74
    include_once $GLOBALS['xoops']->path("modules/" . $module->dirname() . "/class/plugin.php");
75
    include_once $GLOBALS['xoops']->path("modules/" . $module->dirname() . "/include/functions.php");
76
    include_once $GLOBALS['xoops']->path("modules/" . $module->dirname(). "/class/dummy.php");
77
78
    //Create the xsitemap.xml file in the site root
79
    $xsitemap_show = Utility::generateSitemap();
80
    return Utility::saveSitemap($xsitemap_show) ? true : false;
81
    */
82
}
83
84
/**
85
 *
86
 * Prepares system prior to attempting to update module
87
 *
88
 * @param XoopsModule $module
89
 *
90
 * @return bool true if successfully ready to update module, false if not
91
 */
92 View Code Duplication
function xoops_module_pre_update_xsitemap(XoopsModule $module)
0 ignored issues
show
Duplication introduced by
This function 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...
93
{
94
    $moduleDirName = basename(dirname(__DIR__));
95
    /** @var XsitemapUtility $utilityClass */
96
    $utilityClass    = \Utility;
97
    if (!class_exists($utilityClass)) {
98
        xoops_load('utility', $moduleDirName);
99
    }
100
101
    $xoopsSuccess = $utilityClass::checkVerXoops($module);
102
    $phpSuccess   = $utilityClass::checkVerPhp($module);
103
    return $xoopsSuccess && $phpSuccess;
104
}
105
106
/**
107
 *
108
 * Functions to upgrade from previous version of the module
109
 *
110
 * @param XoopsModule $module
111
 * @param int|null        $previousVersion
112
 * @return bool true if successfully updated module, false if not
113
 * @internal param int $curr_version version number of module currently installed
114
 *
115
 */
116
function xoops_module_update_xsitemap(XoopsModule $module, $previousVersion = null)
117
{
118
    /*======================================================================
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% 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...
119
        //----------------------------------------------------------------
120
        // Remove xSitemap uploads folder (and all subfolders) if they exist
121
        //----------------------------------------------------------------*
122
        $utilityClass = ucfirst($moduleDirName) . 'Utility';
123
        if (!class_exists($utilityClass)) {
124
            xoops_load('utility', $moduleDirName);
125
        }
126
127
        // Recursively delete directories
128
        $xsUploadDir = realpath(XOOPS_UPLOAD_PATH . "/" . $module->dirname());
129
        $success = $utilityClass::rrmdir($xsUploadDir);
130
        if (true !== $success) {
131
            \Xmf\Language::load('admin', $module->dirname());
132
            $module->setErrors(sprintf(_AM_XSITEMAP_ERROR_BAD_DEL_PATH, $xsUploadDir));
133
        }
134
        return $success;
135
    ======================================================================*/
136
137
    $moduleDirName = $module->getVar('dirname');
138
    $helper      = \Xmf\Module\Helper::getHelper($moduleDirName);
139
    /** @var XsitemapUtility $utilityClass */
140
    $utilityClass = ucfirst($moduleDirName) . 'Utility';
141
    if (!class_exists($utilityClass)) {
142
        xoops_load('utility', $moduleDirName);
143
    }
144
    //-----------------------------------------------------------------------
145
    // Upgrade for Xsitemap < 1.54
146
    //-----------------------------------------------------------------------
147
148
    $success = true;
149
150
    $helper->loadLanguage('modinfo');
151
    $helper->loadLanguage('admin');
152
153 View Code Duplication
    if ($previousVersion < 154) {
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...
154
        //----------------------------------------------------------------
155
        // Remove previous css & images directories since they've been relocated to ./assets
156
        // Also remove uploads directories since they're no longer used
157
        //----------------------------------------------------------------
158
        $old_directories = [
159
            $helper->path('css/'),
160
            $helper->path('js/'),
161
            $helper->path('images/'),
162
            XOOPS_UPLOAD_PATH . '/' . $module->dirname()
163
        ];
164
        foreach ($old_directories as $old_dir) {
165
            $dirInfo = new SplFileInfo($old_dir);
166
            if ($dirInfo->isDir()) {
167
                // The directory exists so delete it
168
                if (false === $utilityClass::rrmdir($old_dir)) {
169
                    $module->setErrors(sprintf(_AM_XSITEMAP_ERROR_BAD_DEL_PATH, $old_dir));
170
                    return false;
171
                }
172
            }
173
            unset($dirInfo);
174
        }
175
176
        //-----------------------------------------------------------------------
177
        // Remove ./template/*.html (except index.html) files since they've
178
        // been replaced by *.tpl files
179
        // Note: this will also remove /template/xsitemap_style.html since it's no longer used
180
        //-----------------------------------------------------------------------
181
        $path       = $helper->path('templates/');
182
        $unfiltered = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
183
        $iterator   = new RegexIterator($unfiltered, "/.*\.html/");
184
        foreach ($iterator as $name => $fObj) {
185
            if ($fObj->isFile() && ('index.html' !== $fObj->getFilename())) {
186
                if (false === ($success = unlink($fObj->getPathname()))) {
187
                    $module->setErrors(sprintf(_AM_XSITEMAP_ERROR_BAD_REMOVE, $fObj->getPathname()));
188
                    return false;
189
                }
190
            }
191
        }
192
193
        //-----------------------------------------------------------------------
194
        // Now remove a some misc files that were renamed or deprecated
195
        //-----------------------------------------------------------------------
196
        $oldFiles = [
197
            $helper->path('include/install.php'),
198
            $helper->path('class/module.php'),
199
            $helper->path('class/menu.php')
200
        ];
201
        foreach ($oldFiles as $file) {
202
            if (is_file($file)) {
203
                if (false === ($delOk = unlink($file))) {
204
                    $module->setErrors(sprintf(_AM_XSITEMAP_ERROR_BAD_REMOVE, $file));
205
                }
206
                $success = $success && $delOk;
207
            }
208
        }
209
    }
210
    return $success;
211
}
212
213
/**
214
 *
215
 * Function to perform before module uninstall
216
 *
217
 * @param XoopsModule $module
218
 *
219
 * @return bool true if successfully executed, false if not
220
 */
221
function xoops_module_pre_uninstall_xsitemap(XoopsModule $module)
0 ignored issues
show
Unused Code introduced by
The parameter $module is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
222
{
223
    return true;
224
}
225
226
/**
227
 *
228
 * Function to complete upon module uninstall
229
 *
230
 * @param XoopsModule $module
231
 *
232
 * @return bool true if successfully executed uninstall of module, false if not
233
 */
234
function xoops_module_uninstall_xsitemap(XoopsModule $module)
0 ignored issues
show
Coding Style introduced by
xoops_module_uninstall_xsitemap 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...
235
{
236
    //    return true;
237
    $moduleDirName = $module->getVar('dirname');
238
    /** @var XsitemapUtility $utilityClass */
239
    $helper      = \Xmf\Module\Helper::getHelper($moduleDirName);
240
    $utilityClass    =  \Utility;
241
    if (!class_exists($utilityClass)) {
242
        xoops_load('utility', $moduleDirName);
243
    }
244
245
    $success = true;
246
    $helper->loadLanguage('admin');
247
248
    //------------------------------------------------------------------
249
    // Remove xSitemap uploads folder (and all subfolders) if they exist
250
    //------------------------------------------------------------------
251
252
    $old_directories = [$GLOBALS['xoops']->path("uploads/{$moduleDirName}")];
253
    foreach ($old_directories as $old_dir) {
254
        $dirInfo = new SplFileInfo($old_dir);
255
        if ($dirInfo->isDir()) {
256
            // The directory exists so delete it
257
            if (false === $utilityClass::rrmdir($old_dir)) {
258
                $module->setErrors(sprintf(_AM_XSITEMAP_ERROR_BAD_DEL_PATH, $old_dir));
259
                $success = false;
260
            }
261
        }
262
        unset($dirInfo);
263
    }
264
    //------------------------------------------------------------------
265
    // Remove xsitemap.xml from XOOPS root folder if it exists
266
    //------------------------------------------------------------------
267
    $xmlfile = $GLOBALS['xoops']->path('xsitemap.xml');
268
    if (is_file($xmlfile)) {
269
        if (false === ($delOk = unlink($xmlfile))) {
270
            $module->setErrors(sprintf(_AM_XSITEMAP_ERROR_BAD_REMOVE, $xmlfile));
271
        }
272
    }
273
    return $success && $delOk;
0 ignored issues
show
Bug introduced by
The variable $delOk does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
274
}
275