Utility   A
last analyzed

Complexity

Total Complexity 35

Size/Duplication

Total Lines 206
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 121
c 3
b 0
f 0
dl 0
loc 206
rs 9.6
wmc 35

3 Methods

Rating   Name   Duplication   Size   Complexity  
C generateSitemap() 0 75 14
B saveSitemap() 0 39 8
C getSitemap() 0 62 13
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 $xoopsDb */
148
        $xoopsDb       = \XoopsDatabaseFactory::getDatabaseConnection();
149
        $sql       = "SELECT `{$id_name}`, `{$pid_name}`, `{$title_name}` FROM " . $xoopsDb->prefix . "_{$table}";
150
        $result    = $xoopsDb->query($sql);
151
        $objsArray = [];
152
        if ($result) {
153
            while (false !== ($row = $xoopsDb->fetchArray($result))) {
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type true; 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

153
            while (false !== ($row = $xoopsDb->fetchArray(/** @scrutinizer ignore-type */ $result))) {
Loading history...
154
                $objsArray[] = new DummyObject($row, $id_name, $pid_name, $title_name);
155
            }
156
        }
157
        //$sql = "SELECT `{$id_name}`, `{$title_name}` FROM " . $xoopsDb->prefix . "_{$table} WHERE `{$pid_name}`= 0";
158
        // v1.54 added in the event categories are flat (don't support hierarchy)
159
        $sql = "SELECT `{$id_name}`, `{$title_name}` FROM " . $xoopsDb->prefix . "_{$table}";
160
        $sqlWhere = '';
161
        if ($pid_name !== $id_name) {
162
            $sqlWhere = "`{$pid_name}`= 0";
163
        }
164
        if ('' !== $where) {
165
            if ('' !== $sqlWhere) {
166
                $sqlWhere .= ' AND ';
167
            }
168
            $sqlWhere .= $where;
169
        }
170
        if ('' !== $sqlWhere) {
171
            $sql .= " WHERE ($sqlWhere)";
172
        }
173
        if ('' != $order) {
174
            $sql .= " ORDER BY `{$order}`";
175
        }
176
        $result   = $xoopsDb->query($sql);
177
        $i        = 0;
178
        $xsitemap = [];
179
        if ($result) {
180
            while (list($catid, $name) = $xoopsDb->fetchRow($result)) {
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type true; 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

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