Passed
Pull Request — master (#88)
by Michael
13:07
created

SysUtility::truncateHtml()   F

Complexity

Conditions 19
Paths 194

Size

Total Lines 95
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 19
eloc 47
c 1
b 0
f 0
nc 194
nop 5
dl 0
loc 95
rs 3.7333

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 declare(strict_types=1);
2
3
namespace XoopsModules\Tdmdownloads\Common;
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
 * @license      https://www.fsf.org/copyleft/gpl.html GNU public license
20
 * @copyright    https://xoops.org 2000-2020 &copy; XOOPS Project
21
 * @author       ZySpec <[email protected]>
22
 * @author       Mamba <[email protected]>
23
 */
24
25
use Xmf\Request;
26
use XoopsFormEditor;
27
use XoopsModules\Tdmdownloads\{
28
    Helper
29
};
30
31
32
/**
33
 * Class SysUtility
34
 */
35
class SysUtility
36
{
37
    use VersionChecks; //checkVerXoops, checkVerPhp Traits
0 ignored issues
show
introduced by
The trait XoopsModules\Tdmdownloads\Common\VersionChecks requires some properties which are not provided by XoopsModules\Tdmdownloads\Common\SysUtility: $tag_name, $prerelease
Loading history...
38
    use ServerStats; // getServerStats Trait
39
    use FilesManagement; // Files Management Trait
40
41
    //--------------- Common module methods -----------------------------
42
43
    /**
44
     * Access the only instance of this class
45
     *
46
     * @return SysUtility
47
     *
48
     */
49
    public static function getInstance(): SysUtility
50
    {
51
        static $instance;
52
        if (null === $instance) {
53
            $instance = new static();
54
        }
55
56
        return $instance;
57
    }
58
59
    /**
60
     * @param $text
61
     * @param $form_sort
62
     * @return string
63
     */
64
    public static function selectSorting($text, $form_sort): string
65
    {
66
        global $start, $order, $sort;
67
68
        $select_view   = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $select_view is dead and can be removed.
Loading history...
69
        $moduleDirName = \basename(\dirname(__DIR__));
0 ignored issues
show
Unused Code introduced by
The assignment to $moduleDirName is dead and can be removed.
Loading history...
70
        $helper = Helper::getInstance();
71
72
        //$pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . $helper->getConfig('modicons16');
73
        $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

73
        $pathModIcon16 = $helper->url(/** @scrutinizer ignore-type */ $helper->getModule()->getInfo('modicons16'));
Loading history...
74
75
        $select_view = '<form name="form_switch" id="form_switch" action="' . Request::getString('REQUEST_URI', '', 'SERVER') . '" method="post"><span style="font-weight: bold;">' . $text . '</span>';
76
        //$sorts =  $sort ==  'asc' ? 'desc' : 'asc';
77
        if ($form_sort == $sort) {
78
            $sel1 = 'asc' === $order ? 'selasc.png' : 'asc.png';
79
            $sel2 = 'desc' === $order ? 'seldesc.png' : 'desc.png';
80
        } else {
81
            $sel1 = 'asc.png';
82
            $sel2 = 'desc.png';
83
        }
84
        $select_view .= '  <a href="' . Request::getString('SCRIPT_NAME', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=asc"><img src="' . $pathModIcon16 . '/' . $sel1 . '" title="ASC" alt="ASC"></a>';
85
        $select_view .= '<a href="' . Request::getString('SCRIPT_NAME', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=desc"><img src="' . $pathModIcon16 . '/' . $sel2 . '" title="DESC" alt="DESC"></a>';
86
        $select_view .= '</form>';
87
88
        return $select_view;
89
    }
90
91
    /***************Blocks***************/
92
    /**
93
     * @param array $cats
94
     * @return string
95
     */
96
    public static function blockAddCatSelect(array $cats): string
97
    {
98
        $cat_sql = '';
99
        if (\is_array($cats) && !empty($cats)) {
100
            $cat_sql = '(' . \current($cats);
101
            \array_shift($cats);
102
            foreach ($cats as $cat) {
103
                $cat_sql .= ',' . $cat;
104
            }
105
            $cat_sql .= ')';
106
        }
107
108
        return $cat_sql;
109
    }
110
111
    /**
112
     * @param $content
113
     */
114
    public static function metaKeywords($content): void
115
    {
116
        global $xoopsTpl, $xoTheme;
117
        $myts    = \MyTextSanitizer::getInstance();
118
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
119
        if (\is_object($xoTheme)) {
120
            $xoTheme->addMeta('meta', 'keywords', \strip_tags($content));
121
        } else {    // Compatibility for old Xoops versions
122
            $xoopsTpl->assign('xoops_metaKeywords', \strip_tags($content));
123
        }
124
    }
125
126
    /**
127
     * @param $content
128
     */
129
    public static function metaDescription($content): void
130
    {
131
        global $xoopsTpl, $xoTheme;
132
        $myts    = \MyTextSanitizer::getInstance();
133
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
134
        if (\is_object($xoTheme)) {
135
            $xoTheme->addMeta('meta', 'description', \strip_tags($content));
136
        } else {    // Compatibility for old Xoops versions
137
            $xoopsTpl->assign('xoops_metaDescription', \strip_tags($content));
138
        }
139
    }
140
141
    /**
142
     * @param string $tableName
143
     * @param string $columnName
144
     *
145
     * @return array|false
146
     */
147
    public static function enumerate(string $tableName, string $columnName)
148
    {
149
        $table = $GLOBALS['xoopsDB']->prefix($tableName);
150
151
        //    $result = $GLOBALS['xoopsDB']->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
152
        //        WHERE TABLE_NAME = '" . $table . "' AND COLUMN_NAME = '" . $columnName . "'")
153
        //    || exit ($GLOBALS['xoopsDB']->error());
154
155
        $sql    = 'SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "' . $table . '" AND COLUMN_NAME = "' . $columnName . '"';
156
        $result = $GLOBALS['xoopsDB']->query($sql);
157
        if (!$result) {
158
            //            trigger_error($GLOBALS['xoopsDB']->error());
159
            $logger     = \XoopsLogger::getInstance();
160
            $logger->handleError(\E_USER_WARNING, $sql, __FILE__, __LINE__);
161
            return false;
162
        }
163
164
        $row      = $GLOBALS['xoopsDB']->fetchBoth($result);
165
        $enumList = \explode(',', \str_replace("'", '', \mb_substr($row['COLUMN_TYPE'], 5, - 6)));
166
        return $enumList;
167
    }
168
169
170
    /**
171
     * Clone a record in a dB
172
     *
173
     * @TODO need to exit more gracefully on error. Should throw/trigger error and then return false
174
     *
175
     * @param string $tableName name of dB table (without prefix)
176
     * @param string $idField   name of field (column) in dB table
177
     * @param int    $id        item id to clone
178
     *
179
     * @return mixed
180
     */
181
    public static function cloneRecord(string $tableName, string $idField, int $id)
182
    {
183
        $newId = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $newId is dead and can be removed.
Loading history...
184
        $table  = $GLOBALS['xoopsDB']->prefix($tableName);
185
        // copy content of the record you wish to clone
186
        $sql       = "SELECT * FROM $table WHERE $idField='" . (int)$id . "' ";
187
        $tempTable = $GLOBALS['xoopsDB']->fetchArray($GLOBALS['xoopsDB']->query($sql), \MYSQLI_ASSOC);
188
        if (!$tempTable) {
189
            trigger_error($GLOBALS['xoopsDB']->error());
190
        }
191
        // set the auto-incremented id's value to blank.
192
        unset($tempTable[$idField]);
193
        // insert cloned copy of the original  record
194
        $sql    = "INSERT INTO $table (" . \implode(', ', \array_keys($tempTable)) . ") VALUES ('" . \implode("', '", \array_values($tempTable)) . "')";
195
        $result = $GLOBALS['xoopsDB']->queryF($sql);
196
        if (!$result) {
197
            trigger_error($GLOBALS['xoopsDB']->error());
198
        }
199
        // Return the new id
200
        return $GLOBALS['xoopsDB']->getInsertId();
201
    }
202
203
    /**
204
     * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags
205
     * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags
206
     * www.cakephp.org
207
     *
208
     * @TODO: Refactor to consider HTML5 & void (self-closing) elements
209
     * @TODO: Consider using https://github.com/jlgrall/truncateHTML/blob/master/truncateHTML.php
210
     *
211
     * @param string $text         String to truncate.
212
     * @param int    $length       Length of returned string, including ellipsis.
213
     * @param string $ending       Ending to be appended to the trimmed string.
214
     * @param bool   $exact        If false, $text will not be cut mid-word
215
     * @param bool   $considerHtml If true, HTML tags would be handled correctly
216
     *
217
     * @return string Trimmed string.
218
     */
219
    public static function truncateHtml(
220
        string $text,
221
        ?int $length = 100,
222
        ?string $ending = '...',
223
        ?bool $exact = false,
224
        ?bool $considerHtml = true
225
    ): string {
226
        $openTags = [];
227
        if ($considerHtml) {
228
            // if the plain text is shorter than the maximum length, return the whole text
229
            if (\mb_strlen(\preg_replace('/<.*?' . '>/', '', $text)) <= $length) {
230
                return $text;
231
            }
232
            // splits all html-tags to scanable lines
233
            \preg_match_all('/(<.+?' . '>)?([^<>]*)/s', $text, $lines, \PREG_SET_ORDER);
234
            $total_length = \mb_strlen($ending);
0 ignored issues
show
Bug introduced by
It seems like $ending can also be of type null; however, parameter $string of mb_strlen() 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

234
            $total_length = \mb_strlen(/** @scrutinizer ignore-type */ $ending);
Loading history...
235
            //$openTags    = [];
236
            $truncate = '';
237
            foreach ($lines as $line_matchings) {
238
                // if there is any html-tag in this line, handle it and add it (uncounted) to the output
239
                if (!empty($line_matchings[1])) {
240
                    // if it's an "empty element" with or without xhtml-conform closing slash
241
                    if (\preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
242
                        // do nothing
243
                        // if tag is a closing tag
244
                    } elseif (\preg_match('/^<\s*\/(\S+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
245
                        // delete tag from $openTags list
246
                        $pos = \array_search($tag_matchings[1], $openTags, true);
247
                        if (false !== $pos) {
248
                            unset($openTags[$pos]);
249
                        }
250
                        // if tag is an opening tag
251
                    } elseif (\preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $line_matchings[1], $tag_matchings)) {
252
                        // add tag to the beginning of $openTags list
253
                        \array_unshift($openTags, \mb_strtolower($tag_matchings[1]));
254
                    }
255
                    // add html-tag to $truncate'd text
256
                    $truncate .= $line_matchings[1];
257
                }
258
                // calculate the length of the plain text part of the line; handle entities as one character
259
                $content_length = \mb_strlen(\preg_replace('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
260
                if ($total_length + $content_length > $length) {
261
                    // the number of characters which are left
262
                    $left            = $length - $total_length;
263
                    $entities_length = 0;
264
                    // search for html entities
265
                    if (\preg_match_all('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, \PREG_OFFSET_CAPTURE)) {
266
                        // calculate the real length of all entities in the legal range
267
                        foreach ($entities[0] as $entity) {
268
                            if ($left >= $entity[1] + 1 - $entities_length) {
269
                                $left--;
270
                                $entities_length += \mb_strlen($entity[0]);
271
                            } else {
272
                                // no more characters left
273
                                break;
274
                            }
275
                        }
276
                    }
277
                    $truncate .= \mb_substr($line_matchings[2], 0, $left + $entities_length);
278
                    // maximum length is reached, so get off the loop
279
                    break;
280
                }
281
                $truncate     .= $line_matchings[2];
282
                $total_length += $content_length;
283
284
                // if the maximum length is reached, get off the loop
285
                if ($total_length >= $length) {
286
                    break;
287
                }
288
            }
289
        } else {
290
            if (\mb_strlen($text) <= $length) {
291
                return $text;
292
            }
293
            $truncate = \mb_substr($text, 0, $length - \mb_strlen($ending));
294
        }
295
        // if the words shouldn't be cut in the middle...
296
        if (!$exact) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $exact of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
297
            // ...search the last occurance of a space...
298
            $spacepos = \mb_strrpos($truncate, ' ');
299
            if (isset($spacepos)) {
300
                // ...and cut the text in this position
301
                $truncate = \mb_substr($truncate, 0, $spacepos);
302
            }
303
        }
304
        // add the defined ending to the text
305
        $truncate .= $ending;
306
        if ($considerHtml) {
307
            // close all unclosed html-tags
308
            foreach ($openTags as $tag) {
309
                $truncate .= '</' . $tag . '>';
310
            }
311
        }
312
313
        return $truncate;
314
    }
315
316
    /**
317
     * Get correct text editor based on user rights
318
     *
319
     * @param \Xmf\Module\Helper $helper
320
     * @param array|null         $options
321
     *
322
     * @return \XoopsFormDhtmlTextArea|\XoopsFormEditor
323
     */
324
    public static function getEditor(?\Xmf\Module\Helper $helper = null, ?array $options = null)
325
    {
326
        /** @var Helper $helper */
327
        if (null === $options) {
328
            $options           = [];
329
            $options['name']   = 'Editor';
330
            $options['value']  = 'Editor';
331
            $options['rows']   = 10;
332
            $options['cols']   = '100%';
333
            $options['width']  = '100%';
334
            $options['height'] = '400px';
335
        }
336
337
        if (null === $helper) {
338
            $helper = Helper::getInstance();
339
        }
340
341
        $isAdmin = $helper->isUserAdmin();
342
343
        if (\class_exists('XoopsFormEditor')) {
344
            if ($isAdmin) {
345
                $descEditor = new XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorAdmin'), $options, $nohtml = false, $onfailure = 'textarea');
346
            } else {
347
                $descEditor = new XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorUser'), $options, $nohtml = false, $onfailure = 'textarea');
348
            }
349
        } else {
350
            $descEditor = new \XoopsFormDhtmlTextArea(\ucfirst($options['name']), $options['name'], $options['value'], '100%', '100%');
0 ignored issues
show
Bug introduced by
'100%' of type string is incompatible with the type integer expected by parameter $cols of XoopsFormDhtmlTextArea::__construct(). ( Ignorable by Annotation )

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

350
            $descEditor = new \XoopsFormDhtmlTextArea(\ucfirst($options['name']), $options['name'], $options['value'], '100%', /** @scrutinizer ignore-type */ '100%');
Loading history...
Bug introduced by
'100%' of type string is incompatible with the type integer expected by parameter $rows of XoopsFormDhtmlTextArea::__construct(). ( Ignorable by Annotation )

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

350
            $descEditor = new \XoopsFormDhtmlTextArea(\ucfirst($options['name']), $options['name'], $options['value'], /** @scrutinizer ignore-type */ '100%', '100%');
Loading history...
351
        }
352
353
        //        $form->addElement($descEditor);
354
355
        return $descEditor;
356
    }
357
358
    /**
359
     * Check if column in dB table exists
360
     *
361
     * @param string $fieldname name of dB table field
362
     * @param string $table     name of dB table (including prefix)
363
     *
364
     * @return bool true if table exists
365
     * @deprecated
366
     */
367
    public static function fieldExists(string $fieldname, string $table): bool
368
    {
369
        $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1);
370
        \trigger_error(__METHOD__ . " is deprecated, use Xmf\Database\Tables instead - instantiated from {$trace[0]['file']} line {$trace[0]['line']},");
371
372
        $result = $GLOBALS['xoopsDB']->queryF("SHOW COLUMNS FROM   $table LIKE '$fieldname'");
373
        return ($GLOBALS['xoopsDB']->getRowsNum($result) > 0);
374
    }
375
376
377
    /**
378
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
379
     *
380
     * @param string $folder The full path of the directory to check
381
     */
382
    public static function prepareFolder(string $folder): void
383
    {
384
        try {
385
            if (!@\mkdir($folder) && !\is_dir($folder)) {
386
                throw new \RuntimeException(\sprintf('Unable to create the %s directory', $folder));
387
            }
388
            file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
389
        } catch (\Exception $e) {
390
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br>';
391
        }
392
    }
393
394
    /**
395
     * Check if dB table table exists
396
     *
397
     * @param string $tablename dB tablename with prefix
398
     * @return bool true if table exists
399
     */
400
    public static function tableExists(string $tablename): bool
401
    {
402
        $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1);
403
        \trigger_error(__FUNCTION__ . " is deprecated, called from {$trace[0]['file']} line {$trace[0]['line']}");
404
        $GLOBALS['xoopsLogger']->addDeprecated(
405
            \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']}"
406
        );
407
        $result = $GLOBALS['xoopsDB']->queryF("SHOW TABLES LIKE '$tablename'");
408
409
        return $GLOBALS['xoopsDB']->getRowsNum($result) > 0    ;
410
    }
411
412
    /**
413
     * Add a field to a mysql table
414
     *
415
     * @param $field
416
     * @param $table
417
     * @return bool|\mysqli_result
418
     */
419
    public static function addField($field, $table)
420
    {
421
        global $xoopsDB;
422
        return $xoopsDB->queryF('ALTER TABLE ' . $table . " ADD $field;");
423
    }
424
}
425