Passed
Push — master ( c3fe63...2ac8fd )
by Michael
44s queued 11s
created

Utility::getSitemap()   C

Complexity

Conditions 11
Paths 144

Size

Total Lines 57
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 40
c 1
b 0
f 0
nc 144
nop 7
dl 0
loc 57
rs 6.95

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
2
3
namespace XoopsModules\Xsitemap;
4
5
/*
6
 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:  xSitemap
20
 *
21
 * @package      \module\Xsitemap\class
22
 * @license      http://www.fsf.org/copyleft/gpl.html GNU public license
23
 * @copyright    https://xoops.org 2001-2017 &copy; XOOPS Project
24
 * @author       ZySpec <[email protected]>
25
 * @author       Mamba <[email protected]>
26
 * @since        File available since version 1.54
27
 */
28
29
use XoopsModules\Xsitemap\{
30
    Common
31
};
32
/** @var Helper $helper */
33
/** @var PluginHandler $pluginHandler */
34
35
36
$helper        = Helper::getInstance();
37
$moduleDirName = \basename(\dirname(__DIR__));
38
\xoops_loadLanguage('admin', $moduleDirName);
39
//if (!class_exists('DummyObject')) {
40
//    xoops_load('dummy', $moduleDirName);
41
//}
42
43
/**
44
 * Class Utility
45
 */
46
class Utility extends Common\SysUtility
47
{
48
    //--------------- Custom module methods -----------------------------
49
    /**
50
     * Show Site map
51
     *
52
     * @return array
53
     */
54
    public static function generateSitemap()
55
    {
56
        $block         = [];
57
        $moduleDirName = \basename(\dirname(__DIR__));
0 ignored issues
show
Unused Code introduced by
The assignment to $moduleDirName is dead and can be removed.
Loading history...
58
        /** @internal can't use Helper since function called during install
59
         * $helper = \Xmf\Module\Helper::getHelper($moduleDirName);
60
         * $pluginHandler  = $helper->getHandler('Plugin', $moduleDirName);
61
         */
62
        //        xoops_load('plugin', $moduleDirName);
63
        \xoops_load('XoopsModuleConfig');
64
        // Get list of modules admin wants to hide from xsitemap
65
        $invisibleDirnames = empty($GLOBALS['xoopsModuleConfig']['invisible_dirnames']) ? ['xsitemap'] : \explode(',', $GLOBALS['xoopsModuleConfig']['invisible_dirnames'] . ',xsitemap');
66
        $invisibleDirnames = \array_map('\trim', $invisibleDirnames);
67
        $invisibleDirnames = \array_map('\mb_strtolower', $invisibleDirnames);
68
        // Get the mid for any of these modules if they're active and hasmain (visible frontside)
69
        /** @var \XoopsModuleHandler $moduleHandler */
70
        $moduleHandler     = \xoops_getHandler('module');
71
        $invisibleMidArray = [];
72
        foreach ($invisibleDirnames as $hiddenDir) {
73
            $criteria = new \CriteriaCompo(new \Criteria('hasmain', 1));
74
            $criteria->add(new \Criteria('isactive', 1));
75
            $criteria->add(new \Criteria('name', $hiddenDir));
76
            $modObj = $moduleHandler->getByDirname($hiddenDir);
77
            if (false !== $modObj && $modObj instanceof \XoopsModule) {
78
                $invisibleMidArray[] = $modObj->mid();
79
            }
80
        }
81
        // Where user has permissions
82
        /** @var \XoopsGroupPermHandler $grouppermHandler */
83
        $grouppermHandler = \xoops_getHandler('groupperm');
84
        $groups           = ($GLOBALS['xoopsUser'] instanceof \XoopsUser) ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS;
85
        $readAllowed      = $grouppermHandler->getItemIds('module_read', $groups);
86
        $filteredMids     = \array_diff($readAllowed, $invisibleMidArray);
87
        $pluginHandler = Helper::getInstance()->getHandler('Plugin');
88
        $criteria      = new \CriteriaCompo(new \Criteria('hasmain', 1));
89
        $criteria->add(new \Criteria('isactive', 1));
90
        if (\count($filteredMids) > 0) {
91
            $criteria->add(new \Criteria('mid', '(' . \implode(',', $filteredMids) . ')', 'IN'));
92
        }
93
        $modules  = $moduleHandler->getObjects($criteria, true);
94
        $criteria = new \CriteriaCompo();
95
        $criteria->setSort('plugin_id');
96
        $criteria->order = 'ASC';
97
        $pluginObjArray  = $pluginHandler->getAll($criteria);
98
        /** @var array $sublinks */
99
        foreach ($modules as $mid => $modObj) {
100
            $sublinks               = $modObj->subLink();
101
            $modDirName             = $modObj->getVar('dirname', 'n');
102
            $block['modules'][$mid] = [
103
                'id'        => $mid,
104
                'name'      => $modObj->getVar('name'),
105
                'directory' => $modDirName,
106
                'sublinks'  => [],
107
                // init the sublinks array
108
            ];
109
            // Now 'patch' the sublink to include module path
110
            if (\count($sublinks) > 0) {
111
                foreach ($sublinks as $sublink) {
112
                    $block['modules'][$mid]['sublinks'][] = [
113
                        'name' => $sublink['name'],
114
                        'url'  => $GLOBALS['xoops']->url("www/modules/{$modDirName}/{$sublink['url']}"),
115
                    ];
116
                }
117
            }
118
            foreach ($pluginObjArray as $pObj) {
119
                if ((0 == $pObj->getVar('topic_pid')) && \in_array($pObj->getVar('plugin_mod_table'), (array)$modObj->getInfo('tables'))) {
120
                    $objVars = $pObj->getValues();
121
                    if (1 == $objVars['plugin_online']) {
122
                        $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'], $objVars['plugin_where']);
123
                        $block['modules'][$mid]['parent'] = $tmpMap['parent'] ?? null;
124
                    }
125
                }
126
            }
127
        }
128
        return $block;
129
    }
130
131
    /**
132
     * Get the Sitemap
133
     *
134
     * @param        $table
135
     * @param        $id_name
136
     * @param        $pid_name
137
     * @param        $title_name
138
     * @param        $url
139
     * @param string $order
140
     * @param string $where
141
     * @return array sitemap links
142
     */
143
    public static function getSitemap($table, $id_name, $pid_name, $title_name, $url, $order = '', $where = '')
144
    {
145
        require_once XOOPS_ROOT_PATH . '/class/tree.php';
146
        $helper = Helper::getInstance();
147
        /** @var \XoopsMySQLDatabase $xDB */
148
        $xDB       = \XoopsDatabaseFactory::getDatabaseConnection();
149
        $sql       = "SELECT `{$id_name}`, `{$pid_name}`, `{$title_name}` FROM " . $xDB->prefix . "_{$table}";
150
        $result    = $xDB->query($sql);
151
        $objsArray = [];
152
        while (false !== ($row = $xDB->fetchArray($result))) {
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type boolean; however, parameter $result of XoopsMySQLDatabase::fetchArray() does only seem to accept mysqli_result, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

152
        while (false !== ($row = $xDB->fetchArray(/** @scrutinizer ignore-type */ $result))) {
Loading history...
153
            $objsArray[] = new DummyObject($row, $id_name, $pid_name, $title_name);
154
        }
155
        //$sql = "SELECT `{$id_name}`, `{$title_name}` FROM " . $xDB->prefix . "_{$table} WHERE `{$pid_name}`= 0";
156
        // v1.54 added in the event categories are flat (don't support hierarchy)
157
        $sql = "SELECT `{$id_name}`, `{$title_name}` FROM " . $xDB->prefix . "_{$table}";
158
        $sqlWhere = '';
159
        if ($pid_name !== $id_name) {
160
            $sqlWhere = "`{$pid_name}`= 0";
161
        }
162
        if ('' !== $where) {
163
            if ('' !== $sqlWhere) {
164
                $sqlWhere .= " AND ";
165
            }
166
            $sqlWhere .= $where;
167
        }
168
        if ('' !== $sqlWhere) {
169
            $sql .= " WHERE ($sqlWhere)";
170
        }
171
        if ('' != $order) {
172
            $sql .= " ORDER BY `{$order}`";
173
        }
174
        $result   = $xDB->query($sql);
175
        $i        = 0;
176
        $xsitemap = [];
177
        while (list($catid, $name) = $xDB->fetchRow($result)) {
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type boolean; however, parameter $result of XoopsMySQLDatabase::fetchRow() does only seem to accept mysqli_result, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

177
        while (list($catid, $name) = $xDB->fetchRow(/** @scrutinizer ignore-type */ $result)) {
Loading history...
178
            $xsitemap['parent'][$i] = [
179
                'id'    => $catid,
180
                'title' => htmlspecialchars($name, ENT_QUOTES | ENT_HTML5),
181
                'url'   => $url . $catid,
182
            ];
183
            if (($pid_name !== $id_name) && $helper->getConfig('show_subcategories')) {
184
                $j           = 0;
185
                $mytree      = new \XoopsObjectTree($objsArray, $id_name, $pid_name);
186
                $child_array = $mytree->getAllChild($catid);
187
                /** @var \XoopsObject $child */
188
                foreach ($child_array as $child) {
189
                    $xsitemap['parent'][$i]['child'][$j] = [
190
                        'id'    => $child->getVar($id_name),
191
                        'title' => $child->getVar($title_name),
192
                        'url'   => $url . $child->getVar($id_name),
193
                    ];
194
                    ++$j;
195
                }
196
            }
197
            ++$i;
198
        }
199
        return $xsitemap;
200
    }
201
202
    /**
203
     * Save the XML Sitemap
204
     *
205
     * @param array $xsitemap_show
206
     * @return mixed int number of bytes saved | false on failure
207
     */
208
    public static function saveSitemap(array $xsitemap_show)
209
    {
210
        $xml                     = new \DOMDocument('1.0', 'UTF-8');
211
        $xml->preserveWhiteSpace = false;
212
        $xml->formatOutput       = true;
213
        $xml_set                 = $xml->createElement('urlset');
214
        $xml_set->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
215
        if (!empty($xsitemap_show)) {
216
            foreach ($xsitemap_show['modules'] as $mod) {
217
                if ($mod['directory']) {
218
                    $xml_url = $xml->createElement('url');
219
                    $xml_url->appendChild($xml->createComment(htmlspecialchars((\ucwords($mod['name'])) . ' ')));
220
                    $loc = $xml->createElement('loc', htmlspecialchars(($GLOBALS['xoops']->url("www/modules/{$mod['directory']}/index.php"))));
221
                    $xml_url->appendChild($loc);
222
                    $xml_set->appendChild($xml_url);
223
                }
224
                if ($mod['parent'] ?? null) {
225
                    foreach ($mod['parent'] as $parent) {
226
                        $xml_parent = $xml->createElement('url');
227
                        $loc        = $xml->createElement('loc', htmlspecialchars($GLOBALS['xoops']->url("www/modules/{$mod['directory']}/{$parent['url']}")));
228
                        $xml_parent->appendChild($loc);
229
                        $xml_set->appendChild($xml_parent);
230
                    }
231
                    $z = 0;
232
                    //if ($mod["parent"][$z]["child"]) {
233
                    if ($mod['parent'][$z]['child'] ?? null) {
234
                        foreach ($mod['parent'][$z]['child'] as $child) {
235
                            $xml_child = $xml->createElement('url');
236
                            $loc       = $xml->createElement('loc', htmlspecialchars($GLOBALS['xoops']->url("www/modules/{$mod['directory']}/{$child['url']}")));
237
                            $xml_child->appendChild($loc);
238
                            $xml_set->appendChild($xml_child);
239
                        }
240
                        ++$z;
241
                    }
242
                }
243
            }
244
        }
245
        $xml->appendChild($xml_set);
246
        return $xml->save($GLOBALS['xoops']->path('www/xsitemap.xml'));
247
    }
248
}
249