Passed
Pull Request — master (#11)
by Michael
01:53
created

Utility   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 192
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 113
dl 0
loc 192
rs 10
c 2
b 0
f 0
wmc 30

3 Methods

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

149
        while (false !== ($row = $xDB->fetchArray(/** @scrutinizer ignore-type */ $result))) {
Loading history...
150
            $objsArray[] = new Xsitemap\DummyObject($row, $id_name, $pid_name, $title_name);
151
        }
152
        //$sql = "SELECT `{$id_name}`, `{$title_name}` FROM " . $xDB->prefix . "_{$table} WHERE `{$pid_name}`= 0";
153
        // v1.54 added in the event categories are flat (don't support hierarchy)
154
        $sql = "SELECT `{$id_name}`, `{$title_name}` FROM " . $xDB->prefix . "_{$table}";
155
        if ($pid_name !== $id_name) {
156
            $sql .= " WHERE `{$pid_name}`= 0";
157
        }
158
        if ('' != $order) {
159
            $sql .= " ORDER BY `{$order}`";
160
        }
161
        $result   = $xDB->query($sql);
162
        $i        = 0;
163
        $xsitemap = [];
164
        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

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