SysUtility::truncateHtml()   F
last analyzed

Complexity

Conditions 19
Paths 194

Size

Total Lines 86
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 46
dl 0
loc 86
rs 3.7333
c 0
b 0
f 0
cc 19
nc 194
nop 5

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
declare(strict_types=1);
4
5
namespace XoopsModules\Suico\Common;
6
7
/*
8
 Utility Class Definition
9
 You may not change or alter any portion of this comment or credits of
10
 supporting developers from this source code or any supporting source code
11
 which is considered copyrighted (c) material of the original comment or credit
12
 authors.
13
14
 This program is distributed in the hope that it will be useful, but
15
 WITHOUT ANY WARRANTY; without even the implied warranty of
16
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
17
 */
18
19
/**
20
 * @license      https://www.fsf.org/copyleft/gpl.html GNU public license
21
 * @copyright    https://xoops.org 2000-2020 &copy; XOOPS Project
22
 * @author       ZySpec <[email protected]>
23
 * @author       Mamba <[email protected]>
24
 */
25
26
use Xmf\Request;
27
use XoopsFormDhtmlTextArea;
28
use XoopsFormEditor;
29
use XoopsModules\Suico\{
30
    Helper
31
};
32
/** @var Helper $helper */
33
34
/**
35
 * Class SysUtility
36
 */
37
class SysUtility
38
{
39
    use VersionChecks;
0 ignored issues
show
introduced by
The trait XoopsModules\Suico\Common\VersionChecks requires some properties which are not provided by XoopsModules\Suico\Common\SysUtility: $tag_name, $prerelease
Loading history...
40
    use ServerStats;
41
    use FilesManagement;
42
43
    // Files Management Trait
44
    //--------------- Custom module methods -----------------------------
45
    /**
46
     * @param $text
47
     * @param $form_sort
48
     * @return string
49
     */
50
    public static function selectSorting($text, $form_sort)
51
    {
52
        global $start, $order, $file_cat, $sort, $xoopsModule;
53
        $select_view   = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $select_view is dead and can be removed.
Loading history...
54
        $moduleDirName = \basename(\dirname(__DIR__, 2));
0 ignored issues
show
Unused Code introduced by
The assignment to $moduleDirName is dead and can be removed.
Loading history...
55
        $helper        = Helper::getInstance();
56
        //        $pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . $helper->getModule()->getInfo('modicons16');
57
        $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

57
        $pathModIcon16 = $helper->url(/** @scrutinizer ignore-type */ $helper->getModule()->getInfo('modicons16'));
Loading history...
58
        $select_view   = '<form name="form_switch" id="form_switch" action="' . Request::getString('REQUEST_URI', '', 'SERVER') . '" method="post"><span style="font-weight: bold;">' . $text . '</span>';
59
        //$sorts =  $sort ==  'asc' ? 'desc' : 'asc';
60
        if ($form_sort == $sort) {
61
            $sel1 = 'asc' === $order ? 'selasc.png' : 'asc.png';
62
            $sel2 = 'desc' === $order ? 'seldesc.png' : 'desc.png';
63
        } else {
64
            $sel1 = 'asc.png';
65
            $sel2 = 'desc.png';
66
        }
67
        $select_view .= '  <a href="' . Request::getString('PHP_SELF', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=asc"><img src="' . $pathModIcon16 . '/' . $sel1 . '" title="ASC" alt="ASC"></a>';
68
        $select_view .= '<a href="' . Request::getString('PHP_SELF', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=desc"><img src="' . $pathModIcon16 . '/' . $sel2 . '" title="DESC" alt="DESC"></a>';
69
        $select_view .= '</form>';
70
        return $select_view;
71
    }
72
73
    /***************Blocks***************/
74
    /**
75
     * @param array $cats
76
     * @return string
77
     */
78
    public static function blockAddCatSelect($cats)
79
    {
80
        $cat_sql = '';
81
        if (\is_array($cats) && !empty($cats)) {
82
            $cat_sql = '(' . \current($cats);
83
            \array_shift($cats);
84
            foreach ($cats as $cat) {
85
                $cat_sql .= ',' . $cat;
86
            }
87
            $cat_sql .= ')';
88
        }
89
        return $cat_sql;
90
    }
91
92
    /**
93
     * @param $content
94
     */
95
    public static function metaKeywords($content)
96
    {
97
        global $xoopsTpl, $xoTheme;
98
        $myts    = \MyTextSanitizer::getInstance();
99
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
100
        if (null !== $xoTheme && \is_object($xoTheme)) {
101
            $xoTheme->addMeta('meta', 'keywords', \strip_tags($content));
102
        } else {    // Compatibility for old Xoops versions
103
            $xoopsTpl->assign('xoops_metaKeywords', \strip_tags($content));
104
        }
105
    }
106
107
    /**
108
     * @param $content
109
     */
110
    public static function metaDescription($content)
111
    {
112
        global $xoopsTpl, $xoTheme;
113
        $myts    = \MyTextSanitizer::getInstance();
114
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
115
        if (null !== $xoTheme && \is_object($xoTheme)) {
116
            $xoTheme->addMeta('meta', 'description', \strip_tags($content));
117
        } else {    // Compatibility for old Xoops versions
118
            $xoopsTpl->assign('xoops_metaDescription', \strip_tags($content));
119
        }
120
    }
121
122
    /**
123
     * @param $tableName
124
     * @param $columnName
125
     *
126
     * @return array
127
     */
128
    public static function enumerate($tableName, $columnName)
129
    {
130
        $table = $GLOBALS['xoopsDB']->prefix($tableName);
131
        //    $result = $GLOBALS['xoopsDB']->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
132
        //        WHERE TABLE_NAME = '" . $table . "' AND COLUMN_NAME = '" . $columnName . "'")
133
        //    || exit ($GLOBALS['xoopsDB']->error());
134
        $sql    = 'SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "' . $table . '" AND COLUMN_NAME = "' . $columnName . '"';
135
        $result = $GLOBALS['xoopsDB']->query($sql);
136
        if (!$result) {
137
            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...
138
        }
139
        $row      = $GLOBALS['xoopsDB']->fetchBoth($result);
140
        $enumList = \explode(',', \str_replace("'", '', \mb_substr($row['COLUMN_TYPE'], 5, -6)));
141
        return $enumList;
142
    }
143
144
    /**
145
     * @param array|string $tableName
146
     * @param int          $id_field
147
     * @param int          $id
148
     *
149
     * @return mixed
150
     */
151
    public static function cloneRecord($tableName, $id_field, $id)
152
    {
153
        $new_id = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $new_id is dead and can be removed.
Loading history...
154
        $table  = $GLOBALS['xoopsDB']->prefix($tableName);
155
        // copy content of the record you wish to clone
156
        $sql    = "SELECT * FROM $table WHERE $id_field='$id' ";
157
        $result = $GLOBALS['xoopsDB']->query($sql);
158
        if (!$result) {
159
            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...
160
        }
161
        $tempTable = $GLOBALS['xoopsDB']->fetchArray($result, \MYSQLI_ASSOC);
162
163
        // set the auto-incremented id's value to blank.
164
        unset($tempTable[$id_field]);
165
        // insert cloned copy of the original  record
166
        $sql    = "INSERT INTO $table (" . \implode(', ', \array_keys($tempTable)) . ") VALUES ('" . \implode("', '", $tempTable) . "')";
167
        $result = $GLOBALS['xoopsDB']->queryF($sql);
168
        if (!$result) {
169
            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...
170
        }
171
172
        // Return the new id
173
        $new_id = $GLOBALS['xoopsDB']->getInsertId();
174
175
        return $new_id;
176
    }
177
178
    /**
179
     * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags
180
     * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags
181
     * www.cakephp.org
182
     *
183
     * @param string $text         String to truncate.
184
     * @param int    $length       Length of returned string, including ellipsis.
185
     * @param string $ending       Ending to be appended to the trimmed string.
186
     * @param bool   $exact        If false, $text will not be cut mid-word
187
     * @param bool   $considerHtml If true, HTML tags would be handled correctly
188
     *
189
     * @return string Trimmed string.
190
     */
191
    public static function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true)
192
    {
193
        $openTags = [];
194
        if ($considerHtml) {
195
            // if the plain text is shorter than the maximum length, return the whole text
196
            if (\mb_strlen(\preg_replace('/<.*?' . '>/', '', $text)) <= $length) {
197
                return $text;
198
            }
199
            // splits all html-tags to scanable lines
200
            \preg_match_all('/(<.+?' . '>)?([^<>]*)/s', $text, $lines, \PREG_SET_ORDER);
201
            $total_length = mb_strlen($ending);
202
            //$openTags    = [];
203
            $truncate = '';
204
            foreach ($lines as $line_matchings) {
205
                // if there is any html-tag in this line, handle it and add it (uncounted) to the output
206
                if (!empty($line_matchings[1])) {
207
                    // if it's an "empty element" with or without xhtml-conform closing slash
208
                    if (\preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
209
                        // do nothing
210
                        // if tag is a closing tag
211
                    } elseif (\preg_match('/^<\s*\/(\S+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
212
                        // delete tag from $openTags list
213
                        $pos = \array_search($tag_matchings[1], $openTags);
214
                        if (false !== $pos) {
215
                            unset($openTags[$pos]);
216
                        }
217
                        // if tag is an opening tag
218
                    } elseif (\preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $line_matchings[1], $tag_matchings)) {
219
                        // add tag to the beginning of $openTags list
220
                        \array_unshift($openTags, \mb_strtolower($tag_matchings[1]));
221
                    }
222
                    // add html-tag to $truncate'd text
223
                    $truncate .= $line_matchings[1];
224
                }
225
                // calculate the length of the plain text part of the line; handle entities as one character
226
                $content_length = \mb_strlen(\preg_replace('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
227
                if ($total_length + $content_length > $length) {
228
                    // the number of characters which are left
229
                    $left            = $length - $total_length;
230
                    $entities_length = 0;
231
                    // search for html entities
232
                    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)) {
233
                        // calculate the real length of all entities in the legal range
234
                        foreach ($entities[0] as $entity) {
235
                            if ($left >= $entity[1] + 1 - $entities_length) {
236
                                $left--;
237
                                $entities_length += \mb_strlen($entity[0]);
238
                            } else {
239
                                // no more characters left
240
                                break;
241
                            }
242
                        }
243
                    }
244
                    $truncate .= \mb_substr($line_matchings[2], 0, $left + $entities_length);
245
                    // maximum lenght is reached, so get off the loop
246
                    break;
247
                }
248
                $truncate     .= $line_matchings[2];
249
                $total_length += $content_length;
250
                // if the maximum length is reached, get off the loop
251
                if ($total_length >= $length) {
252
                    break;
253
                }
254
            }
255
        } elseif (\mb_strlen($text) <= $length) {
256
            return $text;
257
        }
258
        $truncate = \mb_substr($text, 0, $length - \mb_strlen($ending));
259
        // if the words shouldn't be cut in the middle...
260
        if (!$exact) {
261
            // ...search the last occurance of a space...
262
            $spacepos = \mb_strrpos($truncate, ' ');
263
            if (isset($spacepos)) {
264
                // ...and cut the text in this position
265
                $truncate = \mb_substr($truncate, 0, $spacepos);
266
            }
267
        }
268
        // add the defined ending to the text
269
        $truncate .= $ending;
270
        if ($considerHtml) {
271
            // close all unclosed html-tags
272
            foreach ($openTags as $tag) {
273
                $truncate .= '</' . $tag . '>';
274
            }
275
        }
276
        return $truncate;
277
    }
278
279
    /**
280
     * @param \Xmf\Module\Helper $helper
281
     * @param array|null         $options
282
     * @return \XoopsFormDhtmlTextArea|\XoopsFormEditor
283
     */
284
    public static function getEditor(
285
        $helper = null,
286
        $options = null
287
    ) {
288
        /** @var Helper $helper */
289
        if (null === $options) {
290
            $options           = [];
291
            $options['name']   = 'Editor';
292
            $options['value']  = 'Editor';
293
            $options['rows']   = 10;
294
            $options['cols']   = '100%';
295
            $options['width']  = '100%';
296
            $options['height'] = '400px';
297
        }
298
        if (null === $helper) {
299
            $helper = Helper::getInstance();
300
        }
301
        $isAdmin = $helper->isUserAdmin();
302
        if (\class_exists('XoopsFormEditor')) {
303
            if ($isAdmin) {
304
                $descEditor = new XoopsFormEditor(
305
                    \ucfirst($options['name']), $helper->getConfig(
306
                    'editorAdmin'
307
                ), $options, $nohtml = false, $onfailure = 'textarea'
308
                );
309
            } else {
310
                $descEditor = new XoopsFormEditor(
311
                    \ucfirst($options['name']), $helper->getConfig(
312
                    'editorUser'
313
                ), $options, $nohtml = false, $onfailure = 'textarea'
314
                );
315
            }
316
        } else {
317
            $descEditor = new XoopsFormDhtmlTextArea(
318
                \ucfirst(
319
                    $options['name']
320
                ), $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 $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

320
                ), $options['name'], $options['value'], /** @scrutinizer ignore-type */ '100%', '100%'
Loading history...
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

320
                ), $options['name'], $options['value'], '100%', /** @scrutinizer ignore-type */ '100%'
Loading history...
321
            );
322
        }
323
        //        $form->addElement($descEditor);
324
        return $descEditor;
325
    }
326
327
    /**
328
     * @param $fieldname
329
     * @param $table
330
     *
331
     * @return bool
332
     */
333
    public function fieldExists(
334
        $fieldname,
335
        $table
336
    ) {
337
        global $xoopsDB;
338
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM   ${table} LIKE '${fieldname}'");
339
        return $xoopsDB->getRowsNum($result) > 0;
340
    }
341
}
342