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

functions.php ➔ xsitemapGenerateSitemap()   F

Complexity

Conditions 15
Paths 288

Size

Total Lines 81
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 51
nc 288
nop 0
dl 0
loc 81
rs 3.789
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
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 42 and the first side effect is on line 27.

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
 * ****************************************************************************
4
 * xsitemap - MODULE FOR XOOPS CMS
5
 *
6
 * You may not change or alter any portion of this comment or credits
7
 * of supporting developers from this source code or any supporting source code
8
 * which is considered copyrighted (c) material of the original comment or credit authors.
9
 * This program is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
 * ****************************************************************************
13
 */
14
/**
15
 * Module: xsitemap
16
 *
17
 * @package    module\xsitemap\includes
18
 * @author     XOOPS Module Development Team
19
 * @author     Urbanspaceman (http://www.takeaweb.it)
20
 * @copyright  Urbanspaceman (http://www.takeaweb.it)
21
 * @copyright  XOOPS Project (http://xoops.org)
22
 * @license    http://www.fsf.org/copyleft/gpl.html GNU public license
23
 * @link       http://xoops.org XOOPS
24
 * @since      1.00
25
 */
26
27
defined('XOOPS_ROOT_PATH') || exit('Restricted access');
28
29
if (!isset($moduleDirName)) {
30
    $moduleDirName = basename(dirname(__DIR__));
31
}
32
xoops_loadLanguage('admin', $moduleDirName);
33
if (!class_exists(ucfirst($moduleDirName) . 'DummyObject')) {
34
    xoops_load('dummy', $moduleDirName);
35
}
36
/**
37
 *
38
 * Show Site map
39
 *
40
 * @return array
41
 */
42
function xsitemapGenerateSitemap()
0 ignored issues
show
Coding Style introduced by
xsitemapGenerateSitemap 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...
43
{
44
    $block         = array();
45
    $moduleDirName = basename(dirname(__DIR__));
46
    /** @internal can't use Helper since function called during install
47
     * $xsitemapHelper = \Xmf\Module\Helper::getHelper($moduleDirName);
48
     * $pluginHandler  = $xsitemapHelper->getHandler('plugin', $moduleDirName);
49
     */
50
    xoops_load('plugin', $moduleDirName);
51
52
    // Get list of modules admin wants to hide from xsitemap
53
    $invisibleDirnames = empty($GLOBALS['xoopsModuleConfig']['invisible_dirnames']) ? array('xsitemap') : explode(',', $GLOBALS['xoopsModuleConfig']['invisible_dirnames'] . ',xsitemap');
54
    $invisibleDirnames = array_map('trim', $invisibleDirnames);
55
    $invisibleDirnames = array_map('mb_strtolower', $invisibleDirnames);
56
57
    // Get the mid for any of these modules if they're active and hasmain (visible frontside)
58
    $moduleHandler     = xoops_getHandler('module');
59
    $invisibleMidArray = array();
60
    foreach ($invisibleDirnames as $hiddenDir) {
61
        $criteria = new CriteriaCompo(new Criteria('hasmain', 1));
62
        $criteria->add(new Criteria('isactive', 1));
63
        $criteria->add(new Criteria('name', $hiddenDir));
64
        $modObj = $moduleHandler->getByDirname($hiddenDir);
65
        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...
66
            $invisibleMidArray[] = $modObj->mid();
67
        }
68
    }
69
70
    // Where user has permissions
71
    $modulepermHandler = xoops_getHandler('groupperm');
72
    $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...
73
    $readAllowed       = $modulepermHandler->getItemIds('module_read', $groups);
74
    $filteredMids      = array_diff($readAllowed, $invisibleMidArray);
75
    $pluginHandler     = xoops_getModuleHandler('plugin', $moduleDirName);
76
    $criteria          = new CriteriaCompo(new Criteria('hasmain', 1));
77
    $criteria->add(new Criteria('isactive', 1));
78
    if (count($filteredMids) > 0) {
79
        $criteria->add(new Criteria('mid', '(' . implode(',', $filteredMids) . ')', 'IN'));
80
    }
81
82
    $modules = $moduleHandler->getObjects($criteria, true);
83
84
    $criteria = new CriteriaCompo();
85
    $criteria->setSort('plugin_id');
86
    $criteria->order = 'ASC';
87
    $pluginObjArray  = $pluginHandler->getAll($criteria);
88
89
    foreach ($modules as $mid => $modObj) {
90
        $sublinks               = $modObj->subLink();
91
        $modDirName             = $modObj->getVar('dirname', 'n');
92
        $block['modules'][$mid] = array(
93
            'id'        => $mid,
94
            'name'      => $modObj->getVar('name'),
95
            'directory' => $modDirName,
96
            'sublinks'  => array()
97
            // init the sublinks array
98
        );
99
        // Now 'patch' the sublink to include module path
100
        if (count($sublinks) > 0) {
101
            foreach ($sublinks as $sublink) {
102
                $block['modules'][$mid]['sublinks'][] = array(
103
                    'name' => $sublink['name'],
104
                    'url'  => $GLOBALS['xoops']->url("www/modules/{$modDirName}/{$sublink['url']}")
105
                );
106
            }
107
        }
108
109
        foreach ($pluginObjArray as $pObj) {
110
            if ((0 == $pObj->getVar('topic_pid')) && in_array($pObj->getVar('plugin_mod_table'), (array)$modObj->getInfo('tables'))) {
111
                $objVars = $pObj->getValues();
112
                if (1 == $objVars['plugin_online']) {
113
                    $tmpMap                           = xsitemap_get_map($objVars['plugin_mod_table'], $objVars['plugin_cat_id'], $objVars['plugin_cat_pid'], $objVars['plugin_cat_name'],
114
                                                                         $objVars['plugin_call'], $objVars['plugin_weight']);
115
                    $block['modules'][$mid]['parent'] = isset($tmpMap['parent']) ? $tmpMap['parent'] : null;
116
                }
117
            }
118
        }
119
    }
120
121
    return $block;
122
}
123
124
/**
125
 * Get the Sitemap
126
 *
127
 * @param        $table
128
 * @param        $id_name
129
 * @param        $pid_name
130
 * @param        $title_name
131
 * @param        $url
132
 * @param string $order
133
 * @return array sitemap links
134
 */
135
function xsitemap_get_map($table, $id_name, $pid_name, $title_name, $url, $order = '')
0 ignored issues
show
Coding Style introduced by
xsitemap_get_map 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...
136
{
137
    $xDB  = XoopsDatabaseFactory::getDatabaseConnection();
138
    $myts = MyTextSanitizer::getInstance();
139
140
    $sql       = "SELECT `{$id_name}`, `{$pid_name}`, `{$title_name}` FROM " . $xDB->prefix . "_{$table}";
141
    $result    = $xDB->query($sql);
142
    $objsArray = array();
143
144
    while ($row = $xDB->fetchArray($result)) {
145
        $objsArray[] = new XsitemapDummyObject($row, $id_name, $pid_name, $title_name);
146
    }
147
148
    //$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...
149
    // v1.54 added in the event categories are flat (don't support hierarchy)
150
    $sql = "SELECT `{$id_name}`, `{$title_name}` FROM " . $xDB->prefix . "_{$table}";
151
    if ($pid_name !== $id_name) {
152
        $sql .= " WHERE `{$pid_name}`= 0";
153
    }
154
    if ('' != $order) {
155
        $sql .= " ORDER BY `{$order}`";
156
    }
157
    $result = $xDB->query($sql);
158
159
    $i        = 0;
160
    $xsitemap = array();
161
    while (list($catid, $name) = $xDB->fetchRow($result)) {
162
        $xsitemap['parent'][$i] = array(
163
            'id'    => $catid,
164
            'title' => $myts->htmlSpecialChars($name),
165
            'url'   => $url . $catid
166
        );
167
168
        if ($GLOBALS['xoopsModuleConfig']['show_subcategories'] && ($pid_name !== $id_name)) {
169
            $j           = 0;
170
            $mytree      = new XoopsObjectTree($objsArray, $id_name, $pid_name);
171
            $child_array = $mytree->getAllChild($catid);
172
            foreach ($child_array as $child) {
173
                $xsitemap['parent'][$i]['child'][$j] = array(
174
                    'id'    => $child->getVar($id_name),
175
                    'title' => $child->getVar($title_name),
176
                    'url'   => $url . $child->getVar($id_name)
177
                );
178
                ++$j;
179
            }
180
        }
181
        ++$i;
182
    }
183
184
    return $xsitemap;
185
}
186
187
/**
188
 * Save the XML Sitemap
189
 *
190
 * @param array $xsitemap_show
191
 * @return mixed int number of bytes saved | false on failure
192
 */
193
function xsitemap_save(array $xsitemap_show)
0 ignored issues
show
Coding Style introduced by
xsitemap_save 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...
194
{
195
    $xml                     = new DOMDocument('1.0', 'UTF-8');
196
    $xml->preserveWhiteSpace = false;
197
    $xml->formatOutput       = true;
198
    $xml_set                 = $xml->createElement('urlset');
199
    $xml_set->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
200
201
    if (!empty($xsitemap_show)) {
202
        foreach ($xsitemap_show['modules'] as $mod) {
203
            if ($mod['directory']) {
204
                $xml_url = $xml->createElement('url');
205
                $xml_url->appendChild($xml->createComment(htmlentities(ucwords($mod['name']))));
206
                //                $xml_url->appendChild($xml->createTextNode("<!-- ". htmlentities(ucwords($mod['name'])) . " -->"));
0 ignored issues
show
Unused Code Comprehensibility introduced by
66% 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...
207
                $loc = $xml->createElement('loc', htmlentities($GLOBALS['xoops']->url("www/modules/{$mod['directory']}/index.php")));
208
                $xml_url->appendChild($loc);
209
            }
210
            if (isset($mod['parent']) ? $mod['parent'] : null) {
211 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...
212
                    $xml_parent = $xml->createElement('url');
213
                    $loc        = $xml->createElement('loc', htmlentities($GLOBALS['xoops']->url("www/modules/{$mod['directory']}/{$parent['url']}")));
214
                    $xml_parent->appendChild($loc);
215
                    $xml_url->appendChild($xml_parent);
0 ignored issues
show
Bug introduced by
The variable $xml_url 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...
216
                }
217
                $z = 0;
218
                //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...
219
                if (isset($mod['parent'][$z]['child']) ? $mod['parent'][$z]['child'] : null) {
220 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...
221
                        $xml_child = $xml->createElement('url');
222
                        $loc       = $xml->createElement('loc', htmlentities($GLOBALS['xoops']->url("www/modules/{$mod['directory']}/{$child['url']}")));
223
                        $xml_child->appendChild($loc);
224
                        $xml_url->appendChild($xml_child);
225
                    }
226
                    ++$z;
227
                }
228
            }
229
            $xml_set->appendChild($xml_url);
230
        }
231
    }
232
    $xml->appendChild($xml_set);
233
    return $xml->save($GLOBALS['xoops']->path('www/xsitemap.xml'));
234
}
235