Completed
Push — master ( 243457...d2eaaf )
by Michael
01:33
created

Utility::generateSitemap()   F

Complexity

Conditions 15
Paths 288

Size

Total Lines 86
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 50
nc 288
nop 0
dl 0
loc 86
rs 3.7313
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php namespace Xoopsmodules\xsitemap;
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 43 and the first side effect is on line 28.

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
 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    https://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
use Xmf\Request;
26
use Xoopsmodules\xsitemap\common;
27
28
require_once __DIR__ . '/common/VersionChecks.php';
29
require_once __DIR__ . '/common/ServerStats.php';
30
require_once __DIR__ . '/common/FilesManagement.php';
31
32
//require_once __DIR__ . '/../include/common.php';
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
33
34
$moduleDirName = basename(dirname(__DIR__));
35
xoops_loadLanguage('admin', $moduleDirName);
36
if (!class_exists(ucfirst($moduleDirName) . 'DummyObject')) {
37
    xoops_load('dummy', $moduleDirName);
38
}
39
40
/**
41
 * Class Utility
42
 */
43
class Utility
44
{
45
    use common\VersionChecks; //checkVerXoops, checkVerPhp Traits
46
47
    use common\ServerStats; // getServerStats Trait
48
49
    use common\FilesManagement; // Files Management Trait
50
51
    //--------------- Custom module methods -----------------------------
52
53
/**
54
 *
55
 * Show Site map
56
 *
57
 * @return array
58
 */
59
public static function generateSitemap()
0 ignored issues
show
Coding Style introduced by
generateSitemap 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...
60
{
61
    $block         = [];
62
    $moduleDirName = basename(dirname(__DIR__));
63
    /** @internal can't use Helper since function called during install
64
     * $helper = \Xmf\Module\Helper::getHelper($moduleDirName);
65
     * $pluginHandler  = $helper->getHandler('plugin', $moduleDirName);
66
     */
67
    xoops_load('plugin', $moduleDirName);
68
69
    // Get list of modules admin wants to hide from xsitemap
70
    $invisibleDirnames = empty($GLOBALS['xoopsModuleConfig']['invisible_dirnames']) ? ['xsitemap'] : explode(',', $GLOBALS['xoopsModuleConfig']['invisible_dirnames'] . ',xsitemap');
71
    $invisibleDirnames = array_map('trim', $invisibleDirnames);
72
    $invisibleDirnames = array_map('mb_strtolower', $invisibleDirnames);
73
74
    // Get the mid for any of these modules if they're active and hasmain (visible frontside)
75
    /** @var \XoopsModuleHandler $moduleHandler */
76
    $moduleHandler     = xoops_getHandler('module');
77
    $invisibleMidArray = [];
78
    foreach ($invisibleDirnames as $hiddenDir) {
79
        $criteria = new \CriteriaCompo(new \Criteria('hasmain', 1));
80
        $criteria->add(new \Criteria('isactive', 1));
81
        $criteria->add(new \Criteria('name', $hiddenDir));
82
        $modObj = $moduleHandler->getByDirname($hiddenDir);
83
        if (false !== $modObj && $modObj instanceof \XoopsModule) {
0 ignored issues
show
Bug introduced by
The class XoopsModule 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...
84
            $invisibleMidArray[] = $modObj->mid();
85
        }
86
    }
87
88
    // Where user has permissions
89
    /** @var \XoopsGroupPermHandler $modulepermHandler */
90
    $modulepermHandler = xoops_getHandler('groupperm');
91
    $groups            = ($GLOBALS['xoopsUser'] instanceof \XoopsUser) ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS;
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...
92
    $readAllowed       = $modulepermHandler->getItemIds('module_read', $groups);
93
    $filteredMids      = array_diff($readAllowed, $invisibleMidArray);
94
    /** @var \XsitemapPluginHandler $pluginHandler */
95
    $pluginHandler = xoops_getModuleHandler('plugin', $moduleDirName);
96
    $criteria      = new \CriteriaCompo(new \Criteria('hasmain', 1));
97
    $criteria->add(new \Criteria('isactive', 1));
98
    if (count($filteredMids) > 0) {
99
        $criteria->add(new \Criteria('mid', '(' . implode(',', $filteredMids) . ')', 'IN'));
100
    }
101
102
    /** @var array $modules */
103
    $modules = $moduleHandler->getObjects($criteria, true);
104
105
    $criteria = new \CriteriaCompo();
106
    $criteria->setSort('plugin_id');
107
    $criteria->order = 'ASC';
108
    $pluginObjArray  = $pluginHandler->getAll($criteria);
109
110
    /** @var array $sublinks */
111
    foreach ($modules as $mid => $modObj) {
112
        $sublinks               = $modObj->subLink();
113
        $modDirName             = $modObj->getVar('dirname', 'n');
114
        $block['modules'][$mid] = [
115
            'id'        => $mid,
116
            'name'      => $modObj->getVar('name'),
117
            'directory' => $modDirName,
118
            'sublinks'  => []
119
            // init the sublinks array
120
        ];
121
        // Now 'patch' the sublink to include module path
122
        if (count($sublinks) > 0) {
123
            foreach ($sublinks as $sublink) {
124
                $block['modules'][$mid]['sublinks'][] = [
125
                    'name' => $sublink['name'],
126
                    'url'  => $GLOBALS['xoops']->url("www/modules/{$modDirName}/{$sublink['url']}")
127
                ];
128
            }
129
        }
130
131
        /** @var array $pluginObjArray */
132
        foreach ($pluginObjArray as $pObj) {
133
            if ((0 == $pObj->getVar('topic_pid')) && in_array($pObj->getVar('plugin_mod_table'), (array)$modObj->getInfo('tables'))) {
134
                $objVars = $pObj->getValues();
135
                if (1 == $objVars['plugin_online']) {
136
                    $tmpMap                           = self::getSitemap($objVars['plugin_mod_table'], $objVars['plugin_cat_id'], $objVars['plugin_cat_pid'], $objVars['plugin_cat_name'], $objVars['plugin_call'], $objVars['plugin_weight']);
137
                    $block['modules'][$mid]['parent'] = isset($tmpMap['parent']) ? $tmpMap['parent'] : null;
138
                }
139
            }
140
        }
141
    }
142
143
    return $block;
144
}
145
146
/**
147
 * Get the Sitemap
148
 *
149
 * @param        $table
150
 * @param        $id_name
151
 * @param        $pid_name
152
 * @param        $title_name
153
 * @param        $url
154
 * @param string $order
155
 * @return array sitemap links
156
 */
157
public static function getSitemap($table, $id_name, $pid_name, $title_name, $url, $order = '')
0 ignored issues
show
Coding Style introduced by
getSitemap 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...
158
{
159
    /** @var \XoopsMySQLDatabase $xDB */
160
    $xDB  = \XoopsDatabaseFactory::getDatabaseConnection();
161
    $myts = \MyTextSanitizer::getInstance();
162
163
    $sql       = "SELECT `{$id_name}`, `{$pid_name}`, `{$title_name}` FROM " . $xDB->prefix . "_{$table}";
164
    $result    = $xDB->query($sql);
165
    $objsArray = [];
166
167
    while (false !== ($row = $xDB->fetchArray($result))) {
168
        $objsArray[] = new \XsitemapDummyObject($row, $id_name, $pid_name, $title_name);
169
    }
170
171
    //$sql = "SELECT `{$id_name}`, `{$title_name}` FROM " . $xDB->prefix . "_{$table} WHERE `{$pid_name}`= 0";
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% 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...
172
    // v1.54 added in the event categories are flat (don't support hierarchy)
173
    $sql = "SELECT `{$id_name}`, `{$title_name}` FROM " . $xDB->prefix . "_{$table}";
174
    if ($pid_name !== $id_name) {
175
        $sql .= " WHERE `{$pid_name}`= 0";
176
    }
177
    if ('' != $order) {
178
        $sql .= " ORDER BY `{$order}`";
179
    }
180
    $result = $xDB->query($sql);
181
182
    $i        = 0;
183
    $xsitemap = [];
184
    while (list($catid, $name) = $xDB->fetchRow($result)) {
185
        $xsitemap['parent'][$i] = [
186
            'id'    => $catid,
187
            'title' => $myts->htmlSpecialChars($name),
188
            'url'   => $url . $catid
189
        ];
190
191
        if (($pid_name !== $id_name) && $GLOBALS['xoopsModuleConfig']['show_subcategories']) {
192
            $j           = 0;
193
            $mytree      = new \XoopsObjectTree($objsArray, $id_name, $pid_name);
194
            $child_array = $mytree->getAllChild($catid);
195
            /** @var \XoopsObject $child */
196
            foreach ($child_array as $child) {
197
                $xsitemap['parent'][$i]['child'][$j] = [
198
                    'id'    => $child->getVar($id_name),
199
                    'title' => $child->getVar($title_name),
200
                    'url'   => $url . $child->getVar($id_name)
201
                ];
202
                ++$j;
203
            }
204
        }
205
        ++$i;
206
    }
207
208
    return $xsitemap;
209
}
210
211
/**
212
 * Save the XML Sitemap
213
 *
214
 * @param array $xsitemap_show
215
 * @return mixed int number of bytes saved | false on failure
216
 */
217
public static function saveSitemap(array $xsitemap_show)
0 ignored issues
show
Coding Style introduced by
saveSitemap 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...
218
{
219
    $xml                     = new \DOMDocument('1.0', 'UTF-8');
220
    $xml->preserveWhiteSpace = false;
221
    $xml->formatOutput       = true;
222
    $xml_set                 = $xml->createElement('urlset');
223
    $xml_set->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
224
225
    if (!empty($xsitemap_show)) {
226
        foreach ($xsitemap_show['modules'] as $mod) {
227
            if ($mod['directory']) {
228
                $xml_url = $xml->createElement('url');
229
                $xml_url->appendChild($xml->createComment(htmlentities(ucwords($mod['name']))));
230
                $loc = $xml->createElement('loc', htmlentities($GLOBALS['xoops']->url("www/modules/{$mod['directory']}/index.php")));
231
                $xml_url->appendChild($loc);
232
                $xml_set->appendChild($xml_url);
233
            }
234
            if (isset($mod['parent']) ? $mod['parent'] : null) {
235 View Code Duplication
                foreach ($mod['parent'] as $parent) {
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...
236
                    $xml_parent = $xml->createElement('url');
237
                    $loc        = $xml->createElement('loc', htmlentities($GLOBALS['xoops']->url("www/modules/{$mod['directory']}/{$parent['url']}")));
238
                    $xml_parent->appendChild($loc);
239
                    $xml_set->appendChild($xml_parent);
240
                }
241
                $z = 0;
242
                //if ($mod["parent"][$z]["child"]) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
88% 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...
243
                if (isset($mod['parent'][$z]['child']) ? $mod['parent'][$z]['child'] : null) {
244 View Code Duplication
                    foreach ($mod['parent'][$z]['child'] as $child) {
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...
245
                        $xml_child = $xml->createElement('url');
246
                        $loc       = $xml->createElement('loc', htmlentities($GLOBALS['xoops']->url("www/modules/{$mod['directory']}/{$child['url']}")));
247
                        $xml_child->appendChild($loc);
248
                        $xml_set->appendChild($xml_child);
249
                    }
250
                    ++$z;
251
                }
252
            }
253
        }
254
    }
255
    $xml->appendChild($xml_set);
256
    return $xml->save($GLOBALS['xoops']->path('www/xsitemap.xml'));
257
}
258
}
259