SysUtility   B
last analyzed

Complexity

Total Complexity 50

Size/Duplication

Total Lines 373
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 156
c 1
b 0
f 0
dl 0
loc 373
rs 8.4
wmc 50

13 Methods

Rating   Name   Duplication   Size   Complexity  
A blockAddCatSelect() 0 13 3
A getEditor() 0 33 5
F truncateHtml() 0 95 19
A getInstance() 0 8 2
A metaKeywords() 0 9 2
A tableExists() 0 10 1
A selectSorting() 0 24 4
A metaDescription() 0 9 2
A enumerate() 0 20 2
A cloneRecord() 0 27 4
A fieldExists() 0 7 1
A addField() 0 4 1
A prepareFolder() 0 9 4

How to fix   Complexity   

Complex Class

Complex classes like SysUtility often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SysUtility, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace XoopsModules\Rssfit\Common;
6
7
/*
8
 Utility Class Definition
9
10
 You may not change or alter any portion of this comment or credits of
11
 supporting developers from this source code or any supporting source code
12
 which is considered copyrighted (c) material of the original comment or credit
13
 authors.
14
15
 This program is distributed in the hope that it will be useful, but
16
 WITHOUT ANY WARRANTY; without even the implied warranty of
17
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
18
 */
19
20
/**
21
 *
22
 * @license      https://www.fsf.org/copyleft/gpl.html GNU public license
23
 * @copyright    https://xoops.org 2000-2020 &copy; XOOPS Project
24
 * @author       ZySpec <[email protected]>
25
 * @author       Mamba <[email protected]>
26
 */
27
28
use Xmf\Request;
29
use XoopsFormEditor;
30
use XoopsModules\Rssfit\{
31
    Helper
32
};
33
34
/**
35
 * Class SysUtility
36
 */
37
class SysUtility
38
{
39
    use VersionChecks;
0 ignored issues
show
introduced by
The trait XoopsModules\Rssfit\Common\VersionChecks requires some properties which are not provided by XoopsModules\Rssfit\Common\SysUtility: $tag_name, $prerelease
Loading history...
40
41
    //checkVerXoops, checkVerPhp Traits
42
43
    use ServerStats;
44
45
    // getServerStats Trait
46
47
    use FilesManagement;
48
49
    // Files Management Trait
50
    //    use ModuleStats;    // ModuleStats Trait
51
52
    //--------------- Common module methods -----------------------------
53
54
    /**
55
     * Access the only instance of this class
56
     *
57
     *
58
     */
59
    public static function getInstance(): SysUtility
60
    {
61
        static $instance;
62
        if (null === $instance) {
63
            $instance = new static();
64
        }
65
66
        return $instance;
67
    }
68
69
    public static function selectSorting(string $text, string $form_sort): string
70
    {
71
        global $start, $order, $sort;
72
73
        $selectView   = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $selectView is dead and can be removed.
Loading history...
74
        $helper        = Helper::getInstance();
75
76
        //$pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . $helper->getConfig('modicons16');
77
        $pathModIcon16 = $helper->url($helper->getModule()->getInfo('modicons16'));
0 ignored issues
show
Bug introduced by
It seems like $helper->getModule()->getInfo('modicons16') can also be of type array; however, parameter $url of Xmf\Module\Helper\GenericHelper::url() does only seem to accept string, 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

77
        $pathModIcon16 = $helper->url(/** @scrutinizer ignore-type */ $helper->getModule()->getInfo('modicons16'));
Loading history...
78
79
        $selectView = '<form name="form_switch" id="form_switch" action="' . Request::getString('REQUEST_URI', '', 'SERVER') . '" method="post"><span style="font-weight: bold;">' . $text . '</span>';
80
        //$sorts =  $sort ==  'asc' ? 'desc' : 'asc';
81
        if ($form_sort == $sort) {
82
            $sel1 = 'asc' === $order ? 'selasc.png' : 'asc.png';
83
            $sel2 = 'desc' === $order ? 'seldesc.png' : 'desc.png';
84
        } else {
85
            $sel1 = 'asc.png';
86
            $sel2 = 'desc.png';
87
        }
88
        $selectView .= '  <a href="' . Request::getString('SCRIPT_NAME', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=asc"><img src="' . $pathModIcon16 . '/' . $sel1 . '" title="ASC" alt="ASC"></a>';
89
        $selectView .= '<a href="' . Request::getString('SCRIPT_NAME', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=desc"><img src="' . $pathModIcon16 . '/' . $sel2 . '" title="DESC" alt="DESC"></a>';
90
        $selectView .= '</form>';
91
92
        return $selectView;
93
    }
94
95
    /***************Blocks***************/
96
    public static function blockAddCatSelect(array $cats): string
97
    {
98
        $catSql = '';
99
        if (!empty($cats)) {
100
            $catSql = '(' . \current($cats);
101
            \array_shift($cats);
102
            foreach ($cats as $cat) {
103
                $catSql .= ',' . $cat;
104
            }
105
            $catSql .= ')';
106
        }
107
108
        return $catSql;
109
    }
110
111
    public static function metaKeywords(string $content): void
112
    {
113
        global $xoopsTpl, $xoTheme;
114
        $myts    = \MyTextSanitizer::getInstance();
115
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
116
        if (\is_object($xoTheme)) {
117
            $xoTheme->addMeta('meta', 'keywords', \strip_tags($content));
118
        } else {    // Compatibility for old Xoops versions
119
            $xoopsTpl->assign('xoops_metaKeywords', \strip_tags($content));
120
        }
121
    }
122
123
    public static function metaDescription(string $content): void
124
    {
125
        global $xoopsTpl, $xoTheme;
126
        $myts    = \MyTextSanitizer::getInstance();
127
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
128
        if (\is_object($xoTheme)) {
129
            $xoTheme->addMeta('meta', 'description', \strip_tags($content));
130
        } else {    // Compatibility for old Xoops versions
131
            $xoopsTpl->assign('xoops_metaDescription', \strip_tags($content));
132
        }
133
    }
134
135
    public static function enumerate(string $tableName, string $columnName): ?array
136
    {
137
        $table = $GLOBALS['xoopsDB']->prefix($tableName);
138
139
        //    $result = $GLOBALS['xoopsDB']->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
140
        //        WHERE TABLE_NAME = '" . $table . "' AND COLUMN_NAME = '" . $columnName . "'")
141
        //    || exit ($GLOBALS['xoopsDB']->error());
142
143
        $sql    = 'SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "' . $table . '" AND COLUMN_NAME = "' . $columnName . '"';
144
        $result = $GLOBALS['xoopsDB']->query($sql);
145
        if (!$result instanceof \mysqli_result) {
146
            //            exit($GLOBALS['xoopsDB']->error());
147
            $logger = \XoopsLogger::getInstance();
148
            $logger->handleError(\E_USER_WARNING, $sql, __FILE__, __LINE__);
149
            return null;
150
        }
151
152
        $row      = $GLOBALS['xoopsDB']->fetchBoth($result);
153
        $enumList = \explode(',', \str_replace("'", '', \mb_substr($row['COLUMN_TYPE'], 5, -6)));
154
        return $enumList;
155
    }
156
157
    /**
158
     * Clone a record in a dB
159
     *
160
     * @TODO need to exit more gracefully on error. Should throw/trigger error and then return false
161
     *
162
     * @param string $tableName name of dB table (without prefix)
163
     * @param string $idField   name of field (column) in dB table
164
     * @param int    $id        item id to clone
165
     */
166
    public static function cloneRecord(string $tableName, string $idField, int $id): ?int
167
    {
168
        $newId = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $newId is dead and can be removed.
Loading history...
169
        $tempTable = '';
170
        $table = $GLOBALS['xoopsDB']->prefix($tableName);
171
        // copy content of the record you wish to clone
172
        $sql       = "SELECT * FROM $table WHERE $idField='" . $id . "' ";
173
        $result = $GLOBALS['xoopsDB']->query($sql);
174
175
        if ($result instanceof \mysqli_result) {
176
            $tempTable = $GLOBALS['xoopsDB']->fetchArray($result, \MYSQLI_ASSOC);
177
        }
178
179
         if (!$tempTable) {
180
            exit($GLOBALS['xoopsDB']->error());
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
181
        }
182
        // set the auto-incremented id's value to blank.
183
        unset($tempTable[$idField]);
184
        // insert cloned copy of the original  record
185
        $sql    = "INSERT INTO $table (" . \implode(', ', \array_keys($tempTable)) . ") VALUES ('" . \implode("', '", $tempTable) . "')";
186
        $result = $GLOBALS['xoopsDB']->queryF($sql);
187
        if (!$result) {
188
            exit($GLOBALS['xoopsDB']->error());
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
189
        }
190
        // Return the new id
191
        $newId = $GLOBALS['xoopsDB']->getInsertId();
192
        return $newId;
193
    }
194
195
    /**
196
     * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags
197
     * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags
198
     * www.cakephp.org
199
     *
200
     * @TODO: Refactor to consider HTML5 & void (self-closing) elements
201
     * @TODO: Consider using https://github.com/jlgrall/truncateHTML/blob/master/truncateHTML.php
202
     *
203
     * @param string   $text         String to truncate.
204
     * @param int|null $length       Length of returned string, including ellipsis.
205
     * @param string   $ending       Ending to be appended to the trimmed string.
206
     * @param bool     $exact        If false, $text will not be cut mid-word
207
     * @param bool     $considerHtml If true, HTML tags would be handled correctly
208
     *
209
     * @return string Trimmed string.
210
     */
211
    public static function truncateHtml(
212
        string $text,
213
        ?int $length = 100,
214
        string $ending = '...',
215
        bool $exact = false,
216
        bool $considerHtml = true
217
    ): string {
218
        $openTags = [];
219
        if ($considerHtml) {
220
            // if the plain text is shorter than the maximum length, return the whole text
221
            if (\mb_strlen(\preg_replace('/<.*?' . '>/', '', $text)) <= $length) {
222
                return $text;
223
            }
224
            // splits all html-tags to scanable lines
225
            \preg_match_all('/(<.+?' . '>)?([^<>]*)/s', $text, $lines, \PREG_SET_ORDER);
226
            $totalLength = \mb_strlen($ending);
227
            //$openTags    = [];
228
            $truncate = '';
229
            foreach ($lines as $lineMatchings) {
230
                // if there is any html-tag in this line, handle it and add it (uncounted) to the output
231
                if (!empty($lineMatchings[1])) {
232
                    // if it's an "empty element" with or without xhtml-conform closing slash
233
                    if (\preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $lineMatchings[1])) {
234
                        // do nothing
235
                        // if tag is a closing tag
236
                    } elseif (\preg_match('/^<\s*\/(\S+?)\s*>$/s', $lineMatchings[1], $tagMatchings)) {
237
                        // delete tag from $openTags list
238
                        $pos = \array_search($tagMatchings[1], $openTags, true);
239
                        if (false !== $pos) {
240
                            unset($openTags[$pos]);
241
                        }
242
                        // if tag is an opening tag
243
                    } elseif (\preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $lineMatchings[1], $tagMatchings)) {
244
                        // add tag to the beginning of $openTags list
245
                        \array_unshift($openTags, \mb_strtolower($tagMatchings[1]));
246
                    }
247
                    // add html-tag to $truncate'd text
248
                    $truncate .= $lineMatchings[1];
249
                }
250
                // calculate the length of the plain text part of the line; handle entities as one character
251
                $contentLength = \mb_strlen(\preg_replace('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', ' ', $lineMatchings[2]));
252
                if ($totalLength + $contentLength > $length) {
253
                    // the number of characters which are left
254
                    $left            = $length - $totalLength;
255
                    $entitiesLength = 0;
256
                    // search for html entities
257
                    if (\preg_match_all('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', $lineMatchings[2], $entities, \PREG_OFFSET_CAPTURE)) {
258
                        // calculate the real length of all entities in the legal range
259
                        foreach ($entities[0] as $entity) {
260
                            if ($left >= $entity[1] + 1 - $entitiesLength) {
261
                                $left--;
262
                                $entitiesLength += \mb_strlen($entity[0]);
263
                            } else {
264
                                // no more characters left
265
                                break;
266
                            }
267
                        }
268
                    }
269
                    $truncate .= \mb_substr($lineMatchings[2], 0, $left + $entitiesLength);
270
                    // maximum length is reached, so get off the loop
271
                    break;
272
                }
273
                $truncate     .= $lineMatchings[2];
274
                $totalLength += $contentLength;
275
276
                // if the maximum length is reached, get off the loop
277
                if ($totalLength >= $length) {
278
                    break;
279
                }
280
            }
281
        } else {
282
            if (\mb_strlen($text) <= $length) {
283
                return $text;
284
            }
285
            $truncate = \mb_substr($text, 0, $length - \mb_strlen($ending));
286
        }
287
        // if the words shouldn't be cut in the middle...
288
        if (!$exact) {
289
            // ...search the last occurance of a space...
290
            $spacepos = \mb_strrpos($truncate, ' ');
291
            if (isset($spacepos)) {
292
                // ...and cut the text in this position
293
                $truncate = \mb_substr($truncate, 0, $spacepos);
294
            }
295
        }
296
        // add the defined ending to the text
297
        $truncate .= $ending;
298
        if ($considerHtml) {
299
            // close all unclosed html-tags
300
            foreach ($openTags as $tag) {
301
                $truncate .= '</' . $tag . '>';
302
            }
303
        }
304
305
        return $truncate;
306
    }
307
308
    /**
309
     * Get correct text editor based on user rights
310
     *
311
     * @return \XoopsFormDhtmlTextArea|\XoopsFormEditor
312
     */
313
    public static function getEditor(?\Xmf\Module\Helper $helper = null, ?array $options = null): ?\XoopsFormTextArea
314
    {
315
        $descEditor = null;
316
317
        /** @var Helper $helper */
318
        if (null === $options) {
319
            $options           = [];
320
            $options['name']   = 'Editor';
321
            $options['value']  = 'Editor';
322
            $options['rows']   = 10;
323
            $options['cols']   = '100%';
324
            $options['width']  = '100%';
325
            $options['height'] = '400px';
326
        }
327
328
        if (null === $helper) {
329
            $helper = Helper::getInstance();
330
        }
331
        $isAdmin = $helper->isUserAdmin();
332
333
        if (\class_exists('XoopsFormEditor')) {
334
            if ($isAdmin) {
335
                $descEditor = new \XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorAdmin'), $options, false, 'textarea');
336
            } else {
337
                $descEditor = new \XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorUser'), $options, false, 'textarea');
338
            }
339
        } else {
340
            $descEditor = new \XoopsFormDhtmlTextArea(\ucfirst($options['name']), $options['name'], $options['value']);
341
        }
342
343
        //        $form->addElement($descEditor);
344
345
        return $descEditor;
346
    }
347
348
    /**
349
     * Check if column in dB table exists
350
     *
351
     * @param string $fieldname name of dB table field
352
     * @param string $table     name of dB table (including prefix)
353
     *
354
     * @return bool true if table exists
355
     * @deprecated
356
     */
357
    public static function fieldExists(string $fieldname, string $table): bool
358
    {
359
        $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1);
360
        \trigger_error(__METHOD__ . " is deprecated, use Xmf\Database\Tables instead - instantiated from {$trace[0]['file']} line {$trace[0]['line']},");
361
362
        $result = $GLOBALS['xoopsDB']->queryF("SHOW COLUMNS FROM   $table LIKE '$fieldname'");
363
        return ($GLOBALS['xoopsDB']->getRowsNum($result) > 0);
364
    }
365
366
    /**
367
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
368
     *
369
     * @param string $folder The full path of the directory to check
370
     */
371
    public static function prepareFolder(string $folder): void
372
    {
373
        try {
374
            if (!@\mkdir($folder) && !\is_dir($folder)) {
375
                throw new \RuntimeException(\sprintf('Unable to create the %s directory', $folder));
376
            }
377
            file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
378
        } catch (\Exception $e) {
379
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br>';
380
        }
381
    }
382
383
    /**
384
     * Check if dB table exists
385
     *
386
     * @param string $tablename dB tablename with prefix
387
     * @return bool true if table exists
388
     */
389
    public static function tableExists(string $tablename): bool
390
    {
391
        $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1);
392
        \trigger_error(__FUNCTION__ . " is deprecated, called from {$trace[0]['file']} line {$trace[0]['line']}");
393
        $GLOBALS['xoopsLogger']->addDeprecated(
394
            \basename(\dirname(__DIR__, 2)) . ' Module: ' . __FUNCTION__ . ' function is deprecated, please use Xmf\Database\Tables method(s) instead.' . " Called from {$trace[0]['file']}line {$trace[0]['line']}"
395
        );
396
        $result = $GLOBALS['xoopsDB']->queryF("SHOW TABLES LIKE '$tablename'");
397
398
        return $GLOBALS['xoopsDB']->getRowsNum($result) > 0;
399
    }
400
401
    /**
402
     * Add a field to a mysql table
403
     *
404
     * @return bool|\mysqli_result
405
     */
406
    public static function addField(string $field, string $table)
407
    {
408
        global $xoopsDB;
409
        return $xoopsDB->queryF('ALTER TABLE ' . $table . " ADD $field;");
410
    }
411
}
412