Passed
Push — master ( 05ee30...e8b784 )
by Michael
05:15
created

SysUtility   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 187
Duplicated Lines 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 25
eloc 97
c 1
b 1
f 0
dl 0
loc 187
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
F truncateHtml() 0 107 19
A getEditor() 0 39 5
A fieldExists() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace XoopsModules\Adslight\Common;
6
7
use XoopsFormDhtmlTextArea;
8
use XoopsFormEditor;
9
use XoopsModules\Adslight\Helper;
10
11
/*
12
 Utility Class Definition
13
14
 You may not change or alter any portion of this comment or credits of
15
 supporting developers from this source code or any supporting source code
16
 which is considered copyrighted (c) material of the original comment or credit
17
 authors.
18
19
 This program is distributed in the hope that it will be useful, but
20
 WITHOUT ANY WARRANTY; without even the implied warranty of
21
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
22
 */
23
/**
24
 * @license      https://www.fsf.org/copyleft/gpl.html GNU public license
25
 * @copyright    https://xoops.org 2000-2020 &copy; XOOPS Project
26
 * @author       ZySpec <[email protected]>
27
 * @author       Mamba <[email protected]>
28
 */
29
30
/**
31
 * Class SysUtility
32
 */
33
class SysUtility
34
{
35
    use VersionChecks;
0 ignored issues
show
introduced by
The trait XoopsModules\Adslight\Common\VersionChecks requires some properties which are not provided by XoopsModules\Adslight\Common\SysUtility: $tag_name, $prerelease
Loading history...
36
    use ServerStats;
37
    use FilesManagement;
38
39
    // Files Management Trait
40
41
    /**
42
     * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags
43
     * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags
44
     * www.cakephp.org
45
     *
46
     * @param string $text         String to truncate.
47
     * @param int    $length       Length of returned string, including ellipsis.
48
     * @param string $ending       Ending to be appended to the trimmed string.
49
     * @param bool   $exact        If false, $text will not be cut mid-word
50
     * @param bool   $considerHtml If true, HTML tags would be handled correctly
51
     *
52
     * @return string Trimmed string.
53
     */
54
    public static function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true): string
55
    {
56
        if ($considerHtml) {
57
            // if the plain text is shorter than the maximum length, return the whole text
58
            if (\mb_strlen(
59
                    \preg_replace('/<.*?' . '>/', '', $text)
60
                ) <= $length) {
61
                return $text;
62
            }
63
            // splits all html-tags to scanable lines
64
            \preg_match_all(
65
                '/(<.+?' . '>)?([^<>]*)/s',
66
                $text,
67
                $lines,
68
                \PREG_SET_ORDER
69
            );
70
            $total_length = \mb_strlen($ending);
71
            $open_tags    = [];
72
            $truncate     = '';
73
            foreach ($lines as $line_matchings) {
74
                // if there is any html-tag in this line, handle it and add it (uncounted) to the output
75
                if (!empty($line_matchings[1])) {
76
                    // if it's an "empty element" with or without xhtml-conform closing slash
77
                    if (\preg_match(
78
                        '/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is',
79
                        $line_matchings[1]
80
                    )) {
81
                        // do nothing
82
                        // if tag is a closing tag
83
                    } elseif (\preg_match('#^<\s*\/(\S+?)\s*>$#s', $line_matchings[1], $tag_matchings)) {
84
                        // delete tag from $open_tags list
85
                        $pos = \array_search($tag_matchings[1], $open_tags, true);
86
                        if (false !== $pos) {
87
                            unset($open_tags[$pos]);
88
                        }
89
                        // if tag is an opening tag
90
                    } elseif (\preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $line_matchings[1], $tag_matchings)) {
91
                        // add tag to the beginning of $open_tags list
92
                        \array_unshift(
93
                            $open_tags,
94
                            \mb_strtolower($tag_matchings[1])
95
                        );
96
                    }
97
                    // add html-tag to $truncate'd text
98
                    $truncate .= $line_matchings[1];
99
                }
100
                // calculate the length of the plain text part of the line; handle entities as one character
101
                $content_length = \mb_strlen(
102
                    \preg_replace('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2])
103
                );
104
                if ($total_length + $content_length > $length) {
105
                    // the number of characters which are left
106
                    $left            = $length - $total_length;
107
                    $entities_length = 0;
108
                    // search for html entities
109
                    if (\preg_match_all(
110
                        '/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i',
111
                        $line_matchings[2],
112
                        $entities,
113
                        \PREG_OFFSET_CAPTURE
114
                    )) {
115
                        // calculate the real length of all entities in the legal range
116
                        foreach ($entities[0] as $entity) {
117
                            if ($left >= $entity[1] + 1 - $entities_length) {
118
                                $left--;
119
                                $entities_length += \mb_strlen($entity[0]);
120
                            } else {
121
                                // no more characters left
122
                                break;
123
                            }
124
                        }
125
                    }
126
                    $truncate .= \mb_substr($line_matchings[2], 0, $left + $entities_length);
127
                    // maximum lenght is reached, so get off the loop
128
                    break;
129
                }
130
                $truncate     .= $line_matchings[2];
131
                $total_length += $content_length;
132
                // if the maximum length is reached, get off the loop
133
                if ($total_length >= $length) {
134
                    break;
135
                }
136
            }
137
        } else {
138
            if (\mb_strlen($text) <= $length) {
139
                return $text;
140
            }
141
            $truncate = \mb_substr($text, 0, $length - \mb_strlen($ending));
142
        }
143
        // if the words shouldn't be cut in the middle...
144
        if (!$exact) {
145
            // ...search the last occurance of a space...
146
            $spacepos = \mb_strrpos($truncate, ' ');
147
            if (isset($spacepos)) {
148
                // ...and cut the text in this position
149
                $truncate = \mb_substr($truncate, 0, $spacepos);
150
            }
151
        }
152
        // add the defined ending to the text
153
        $truncate .= $ending;
154
        if ($considerHtml) {
155
            // close all unclosed html-tags
156
            foreach ($open_tags as $tag) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $open_tags does not seem to be defined for all execution paths leading up to this point.
Loading history...
157
                $truncate .= '</' . $tag . '>';
158
            }
159
        }
160
        return $truncate;
161
    }
162
163
    /**
164
     * @param null       $helper
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $helper is correct as it would always require null to be passed?
Loading history...
165
     * @param array|null $options
166
     * @return XoopsFormDhtmlTextArea|XoopsFormEditor
167
     */
168
    public static function getEditor($helper = null, $options = null)
169
    {
170
        /** @var Helper $helper */
171
        if (!\is_object($helper)) {
172
            $helper = Helper::getInstance();
173
        }
174
        if (null === $options) {
175
            $options           = [];
176
            $options['name']   = 'Editor';
177
            $options['value']  = 'Editor';
178
            $options['rows']   = 10;
179
            $options['cols']   = '100%';
180
            $options['width']  = '100%';
181
            $options['height'] = '400px';
182
        }
183
        $isAdmin = $helper->isUserAdmin();
184
        if (\class_exists('XoopsFormEditor')) {
185
            if ($isAdmin) {
186
                $descEditor = new \XoopsFormEditor(
187
                    \ucfirst($options['name']), $helper->getConfig(
188
                    'editorAdmin'
189
                ),  $options, $nohtml = false, $onfailure = 'textarea'
190
                );
191
            } else {
192
                $descEditor = new \XoopsFormEditor(
193
                    \ucfirst($options['name']), $helper->getConfig(
194
                    'editorUser'
195
                ),  $options, $nohtml = false, $onfailure = 'textarea'
196
                );
197
            }
198
        } else {
199
            $descEditor = new \XoopsFormDhtmlTextArea(
200
                \ucfirst(
201
                    $options['name']
202
                ), $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

202
                ), $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

202
                ), $options['name'], $options['value'], '100%', /** @scrutinizer ignore-type */ '100%'
Loading history...
203
            );
204
        }
205
        //        $form->addElement($descEditor);
206
        return $descEditor;
207
    }
208
209
    /**
210
     * @param $fieldname
211
     * @param $table
212
     *
213
     * @return bool
214
     */
215
    public function fieldExists($fieldname, $table): bool
216
    {
217
        global $xoopsDB;
218
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM   ${table} LIKE '${fieldname}'");
219
        return $xoopsDB->getRowsNum($result) > 0;
220
    }
221
}
222